Perl 线程之间的共享套接字对象 [英] Shared socket object among Perl threads
问题描述
我正在尝试创建一个可以在线程之间共享的套接字对象.以下代码不起作用,因为套接字对象是一个 GLOB.如何共享套接字对象?可以这样吗?
I am trying to create a socket object that can be shared among threads. The following code does not work because socket object is a GLOB. How could the socket object be shared? Can it be done this way?
my $socket1 = IO::Socket::INET->new(
Proto => "tcp",
PeerAddr => "localhost",
PeerPort => "888",
) or die "couldn't connect: $!";
my $socket_shared =shared_clone($socket1);
....
my $thr1 = threads->create(\&Thread_1);
$thr1->join();
sub Thread_1 {
lock($socket_cpy);
my $data = "Msg.\n";
$socket1->send($data);
$socket1->recv($data,1024);
}
错误:不支持的引用类型:GLOB 在第 7 行(此处为调用 shared_clone 的地方).
ERROR: Unsupported ref type: GLOB at line (7 here, where the shared_clone is called).
推荐答案
我可以建议您不要尝试在线程之间共享套接字吗?这感觉就像是在要求它们之间存在并发问题.
Can I suggest instead that you don't try and share a socket between threads? That feels like something that's going to be asking for concurrency issues between them.
虽然有(可能)这样做的方法,但我建议改为 - 为 IO 设置一个负责"的单线程,并使用类似 Thread::Queue
的东西与之交互.
Whilst there are (probably) ways of doing that, I'd suggest instead - have a single thread 'responsible' for the IO, and use something like Thread::Queue
to interact with it.
例如类似的东西:
use strict;
use warnings;
use threads;
use Thread::Queue;
my $output_q = Thread::Queue->new();
my $nthreads = 1;
sub socket_thread {
my $socket1 = IO::Socket::INET->new(
Proto => "tcp",
PeerAddr => "localhost",
PeerPort => "888",
) or die "couldn't connect: $!";
while ( my $data = $output_q->dequeue() ) {
$socket1->send($data);
$socket1->recv( $data, 1024 );
}
}
sub worker_thread {
$output_q->enqueue( "Some text from thread: ",
threads->self->tid(), "\n" );
}
for ( 1 .. $nthreads ) {
threads->create( \&worker_thread );
}
foreach my $thr ( threads->list() ) {
$thr->join();
}
那样你根本不需要传递套接字,你可以使用一个或多个队列来序列化你的 IO.这 - 在我看来 - 是首先在 perl 中线程化的更有力的原因之一 - 你有更好的 IPC 机制可以使用.
That way you don't need to pass the socket around at all, you can use one or more queues to serialise your IO. This - to my mind - is one of the stronger reasons to thread in perl in the first place - you've better IPC mechanisms to work with.
否则我很想建议使用 fork,它(在 Unix 上)通常更有效.
Otherwise I'd be tempted to suggest using forks, which (on Unix) are generally more efficient.
这篇关于Perl 线程之间的共享套接字对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!