简体   繁体   English

Pthread服务器编程:如何释放在recv调用中被阻塞以处理来自另一个线程的请求的线程

[英]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. 我有一个简单的服务器程序,使用pthread lib在Debian上用C编写。 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. 现在,在某个时候,每个线程都会在recv()上阻塞,以等待任何客户端文件请求。 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? 由于所有线程均在recv()调用中被阻止,因此其他线程如何才能注意到它们必须向正在处理的客户端请求文件? Is there any way to "interrupt" the recv(), serve the request and then go back to the recv()? 有什么方法可以“中断” recv(),处理请求,然后返回到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. 执行此操作的经典方法是为每个线程创建一个pipe() ,而不是在recv()调用上进行阻塞,而poll()的线程将在监视套接字和管道的读取结束文件描述符的同时进行阻塞。 When poll() returns, if the socket is readable then call recv() ; poll()返回时,如果套接字可读,则调用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. 当您要向另一个线程发出请求时,可以通过写入该线程的管道将其唤醒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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