Mutex blocking and a number of threads

I have an API (written in C

) that allows any number of incoming (concurrent) connections. Each connection is handled by an independent pthread

one generated whenever a client connects to the API. Each of these connections can (but need not) change the properties of the server so that requests do not need to 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);
}

      

Suppose you are processing one request that takes a long time (for example, ten seconds). At this time, five more requests come in, so five more pthreads

will be available in the function pthread_mutex_lock

.

  • Do they just wait there and proceed as directed (one by one served)?

The reason I am asking is what I would expect, but I have not found an example with more than one parallel thread in the official documentation.

  • Is there a guarantee that requests will be processed in the same order in which they were received, or will one of the five waiting threads be allowed to start after a long request has completed?

My code does not need a strict order of execution, but I would like to know in advance what to expect in order to develop the code correctly.

I've also read about recursive mutex

, but I'd like to avoid them for a number of reasons. Also, my code won't try to block multiple times from one pthread

by design.

+3


source to share


1 answer


The mutex ensures that exactly one thread enters a critical section of your code, in your case, a call process_request()

at a time. When a thread t

acquires a lock, any subsequent thread must wait until t

it releases it.



If several such threads arrive, who gets the opportunity to go first depends on the scheduling of threads by the operating system, which is not deterministic and can be different each time the program is run. However, the guarantee is that only one stream will go through each time.

+2


source







All Articles