go ahead... be a heretic | |
PerlMonks |
Socket client thread design problemby photron (Novice) |
on Mar 20, 2014 at 14:19 UTC ( [id://1079081]=perlquestion: print w/replies, xml ) | Need Help?? |
photron has asked for the wisdom of the Perl Monks concerning the following question: I'm currently porting some C code to Perl and ran into problems in the socket and thread handling design. I want to ask for some guidance. First I ran into problems with the differences in the threading model of C and Perl. The existing C code uses a socket and shares it between multiple threads. This doesn't work directly in Perl. Due to the way Perl clones variables on thread creation a threads->create call blocks on Windows if another thread is doing a blocking receive on the socket. So I need to avoid this situation by ensuring that the receive thread is not running while other threads are created. This was tricky but I managed to get it working. But there are still other problems due to the way the C code works. I spent some days on this problem and now think that it's impossible to implement the behavior of the C code in Perl. The behavior of the C code is as follows: The user can send request to a server and receive responses. The server can also send spontaneous responses that are call callbacks. The API has a method to establish the socket connection and create a receive and a callback thread. The receive thread does a blocking recv() call on the socket and handles the incoming data. If the incoming data is a response then it is passed back to user via a queue. If it's a callback then it is handed over to the callback thread that will call a user-provide subroutine to handle it. So the socket is shared between three threads. Then there is auto-reconnect handling. If the socket gets disconnected from the server then this is detected by the receive thread which will then tell the callback thread to try to reconnect. And this is the problem: Once the connection gets established again, only the callback thread has the correct socket. The receive thread and the main thread of the program that's running the user code have old sockets. I tried to share the socket's fileno between the threads and fdopen sockets based on the fileno. But this gets hairy quickly and I still ran into threads->create blocking in Windows. So any advise on realizing this behavior without running into all this trouble created by the differences in the threading model of C and Perl?
Back to
Seekers of Perl Wisdom
|
|