简体   繁体   中英

Pthread server programming: how to release a thread which is blocked on a recv call to handle a request from another thread

I have a simple server program, written in C on Debian using the pthread lib. The program handles the communication between some clients which want to share files. For each client there is a handler thread. Now, at some point, each thread will block on recv() waiting for any client file requests. If one of the clients asks for a specific file owned, by another client, the server has to get this file from its owner, through its handler thread, and then deliver the file to the client which requested it, through its handler thread. As all the threads are blocked on the recv() calls, how can they be noticed by other threads that they have to request a file to the client they are handling? Is there any way to "interrupt" the recv(), serve the request and then go back to the recv()?

The classic way to do this is to create a pipe() for each thread, and instead of blocking on the recv() call, the thread blocks in poll() monitoring both the socket and the read end file descriptor of the pipe. When poll() returns, if the socket is readable then call recv() ; if the pipe is readable then read from it and check for requests from other threads.

When you want to make a request to another thread, you can wake it up by writing to that thread's pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM