[英]Mutex lock and a number of threads
I have an API (written in C
) that permits any number of incoming (concurrent) connections. 我有一个API(用
C
编写),允许任意数量的传入(并发)连接。 Each connection is handled by an independet pthread
created whenever a client connects to the API. 每当客户端连接到API时,每个连接都由一个独立的
pthread
处理。 Each of these connections can (but do not have to) change properties of the server such that requests should not be processed at the same time. 这些连接中的每一个都可以(但不必)更改服务器的属性,以便不应同时处理请求。
My code basically follows this structure: 我的代码基本上遵循这个结构:
pthread_mutex_t lock;
void request_handler(char * request)
{
pthread_mutex_lock(&lock);
process_request(request);
pthread_mutex_unlock(&lock);
}
Assume now one request is being processed that takes a long time (eg ten seconds). 现在假设正在处理一个需要很长时间(例如十秒)的请求。 In this time, five other requests come in, so five additional
pthreads
will reach at the pthread_mutex_lock
function. 在这个时候,有五个其他请求进入,因此
pthread_mutex_lock
函数将会有另外五个pthreads
。
The reason why I'm asking this is that this is what I'd expect but I haven't found an example with more than one concurrent thread in the official documentation. 我问这个的原因是这是我所期望的,但我没有找到官方文档中有多个并发线程的示例。
Strict in-order execution is not needed by my code, but I'd like to know beforehand what to expect in order to design my code properly. 不需要严格的顺序执行我的代码,但我想知道,以正确设计我的代码,以期望事先什么。
I also read about recursive mutex
, but I'd like to avoid them due to a number of reasons. 我也读过有关递归
mutex
,但由于种种原因,我想避免使用它们。 Furthermore, my code will not try to lock multiple times from one single pthread
by construction. 此外,我的代码不会尝试通过构造从一个单独的
pthread
锁定多次。
The mutex ensures that exactly one thread enters the critical section of your code, in your case, the call to process_request()
, at a time. 互斥锁确保只有一个线程进入代码的关键部分,在您的情况下,一次调用
process_request()
。 Once a thread t
obtains the lock, any subsequent thread must wait until t
releases it. 一旦线程
t
获得锁,任何后续的线程必须等待,直到t
释放它。
If multiple such threads arrive, who gets a chance to go first depends on the scheduling of the threads by the operating system, which is not deterministic and can be different each time you run the program. 如果多个这样的线程到达,谁有机会先行取决于操作系统对线程的调度,这不是确定性的,并且每次运行程序时都可能不同。 However, the guarantee is that it will be only one thread that can pass, each time.
但是,保证每次只能传递一个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.