[英]How to share a filehandle between threads in Perl?
I have two threads, 我有两个线程,
One runs a loop with HTTP::Daemon, and the other runs a IO::Select based socket server. 一个运行带有HTTP :: Daemon的循环,另一个运行基于IO :: Select的套接字服务器。
Now when user connects to the HTTP service it will need to write to the client of the socket server. 现在,当用户连接到HTTP服务时,它将需要写入套接字服务器的客户端。
However, in Perl I cannot share a filehandle with threads::shared
. 但是,在Perl中,我无法与
threads::shared
文件句柄。
Any suggestions? 有什么建议么?
File descriptors are global to the process and you can dereference a filehandle to its descriptor using fileno
. 文件描述符是进程的全局,您可以使用
fileno
将文件句柄取消引用到其描述符。 Then it's just a matter of passing that simple scalar value between threads and reopening by number. 然后,它只是在线程之间传递这个简单的标量值并按数字重新打开。
In your HTTP::Daemon
thread: 在您的
HTTP::Daemon
线程中:
my $fileno = fileno $fh;
The pass the number to the IO::Select
thread by whatever means your program is using (eg a shared array). 通过程序使用的任何方式将数字传递给
IO::Select
线程(例如共享数组)。 And reopen the handle by number in the IO::Select
thread: 并在
IO::Select
线程中按编号重新打开句柄:
open my $fh, "&=$fileno";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.