in reply to Re^4: multithreaded tcp listener with IO::Socket
in thread multithreaded tcp listener with IO::Socket
This is a known problem. The solution is to pass the fileno( $socket ) bwtween the threads. As this is just an integer, it bypasses the restrictions on shared variables. Once you get the fileno in the destination thread, you can re-open the socket there and use it in the normal ways.
See Re: FileHandles and threads & Re^3: Passing globs between threads for some background and example code, plus some discussion of the caveats. The main problem with this approach is that you have to ensure that the socket returned by accept() does not go out of scope (causing the socket to be closed), before the thread has had chance to reopen it. That's easily achieved by pushing a copy of the socket handle into a (non-shared) array in the accept thread, as well as queueing it.
However, you then have to arrange for those copies to be cleaned up so that you do not leak handles. The method I've evolved to handle that, involves saving copies of the handles in the accept thread as the values in a non-shared hash, keyed by the fileno. Once the client thread has finished with the thread, it closes it's handle and queues the fileno back to the accept thread which use it to close the original handle as a part of the acceppt loop.
It sounds complicated, but is actually easier to code than describe. I'll clean up one of my test programs and post it later today.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^6: multithreaded tcp listener with IO::Socket
by Random_Walk (Prior) on May 18, 2006 at 12:59 UTC | |
by BrowserUk (Patriarch) on May 18, 2006 at 13:31 UTC | |
by txemy (Initiate) on Nov 15, 2010 at 10:48 UTC | |
by BrowserUk (Patriarch) on Nov 15, 2010 at 12:02 UTC | |
by txemy (Initiate) on Nov 15, 2010 at 12:52 UTC |