Sebastian Weber wrote:
> The following code sets up a UNIX domain socket server 
>
<http://www.experts-exchange.com/Programming/Programming_Languages/Perl/Q_22001649.html#>
> 
> and connects to that server in a different thread. I found the
> following 
> code using threads to block forever - ist blocks exactly at the
> connect 
> / accept calls:
> 
> #!/usr/bin/perl
> use threads;
> use Socket;
> 
> unlink ("/tmp/mysock");
> $t=threads->create("con_thread");
> 
> socket (SOCK1,PF_UNIX,SOCK_STREAM,0) or die "socket(): $!";
> bind (SOCK1, sockaddr_un("/tmp/mysock")) or die "bind(): $!";
> listen(SOCK1,SOMAXCONN) or die "listen(): $!";
> accept (CLIENT,SOCK1);
> $t->join();
> 
> sub con_thread {
>      sleep(2);
>      socket(SOCK2, PF_UNIX, SOCK_STREAM, 0) or die "socket(): $!";
>      connect(SOCK2, sockaddr_un("/tmp/mysock")) or die "connect():
> $!";
> }
> 
> Whereas the same code will not block using fork():
> 
> #!/usr/bin/perl
> use threads;
> use Socket;
> 
> unlink ("/tmp/mysock");
> if (fork) {con_thread();exit;}
> 
> socket (SOCK1,PF_UNIX,SOCK_STREAM,0) or die "socket(): $!";
> bind (SOCK1, sockaddr_un("/tmp/mysock")) or die "bind(): $!";
> listen(SOCK1,SOMAXCONN) or die "listen(): $!";
> accept (CLIENT,SOCK1);
> 
> sub con_thread {
>      sleep(2);
>      socket(SOCK2, PF_UNIX, SOCK_STREAM, 0) or die "socket(): $!";
>      connect(SOCK2, sockaddr_un("/tmp/mysock")) or die "connect():
> $!";
> }
> 
> Does anybody have any idea why?? Is there a workaround?
> BTW: Im using Perl v5.8.7 built for cygwin-thread-multi-64int

The problem is that Socket is not thread-safe.  You can work around
this by loading Socket into the main thread after creating the child
thread, and loading it separately in the child thread:

#!/usr/bin/perl

use threads;

unlink ("/tmp/mysock");
my $t=threads->create("con_thread");

require Socket;
import Socket ':all';

socket (SOCK1,PF_UNIX,SOCK_STREAM,0) or die "socket(): $!";
bind (SOCK1, sockaddr_un("/tmp/mysock")) or die "bind(): $!";
listen(SOCK1,SOMAXCONN) or die "listen(): $!";
accept (CLIENT,SOCK1);

$t->join();

sub con_thread {
    require Socket;
    import Socket ':all';

    sleep(2);
    socket(SOCK2, PF_UNIX, SOCK_STREAM, 0) or die "socket(): $!";
    connect(SOCK2, sockaddr_un("/tmp/mysock")) or die "connect(): $!";
}



 
____________________________________________________________________________________
Do you Yahoo!?
Everyone is raving about the all-new Yahoo! Mail beta.
http://new.mail.yahoo.com

Reply via email to