inductor has asked for the wisdom of the Perl Monks concerning the following question:

Hi all. I`m trying to open a socket in a thread, like this:
use threads; use threads::shared; use IO::Socket; my $feed = threads->new (\&getData); sub getData { my $remote = IO::Socket::INET->new("somehost:port") or die "Can`t +open feed\n"; print "Foo.\n"; while ( <$remote> ) { print } }
When I run script, it quits immediately, not ever printing "Foo." to stdout. If I do '$feed->join', script works, but I don`t want to pause main program until this thread finishes. Is it possible to use IO::Socket within a thread? Thanks in advance, and sorry for terrible English.

Replies are listed 'Best First'.
Re: Working with IO::Socket in thread.
by BrowserUk (Patriarch) on Sep 23, 2005 at 12:12 UTC
    You're starting your thread and then your main thread does nothing else, so it just runs off the end of the script and the whole script terminates.

    Try adding  sleep 60; after you create the thread. The program will then read and display any input from the socket for 60 seconds before terminating.

    Of course, normally your main thread would go about doing whatever else it should be doing, the sleep is just to demonstrate the problem with your code as posted.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
Re: Working with IO::Socket in thread.
by pg (Canon) on Sep 23, 2005 at 12:06 UTC

    Yes, your script will not work. Once the main thread starts the child thread for getData(), it will quit, as it has done eveything it supposed to do. That's why add join() fix it.

    What's the problem to leave the main thread running? Add join is the right thing to do.

Re: Working with IO::Socket in thread.
by castaway (Parson) on Sep 23, 2005 at 11:16 UTC
    That code should work.

    Does your perl binary actually have threads compiled in? Try looking at the output of perl -V and see if it claims usethreads=define in it somewhere? If it says undef, you need to get a new perl or recompile yours.

    C.

Re: Working with IO::Socket in thread.
by inductor (Novice) on Sep 26, 2005 at 08:00 UTC
    I`ve added huge delay in main thread, and it worked. Thanks a lot!