Pthread Mutex lock unlock by different threads

前端 未结 3 1039
既然无缘
既然无缘 2020-12-02 23:47

A Naive question ..

I read before saying - \"A MUTEX has to be unlocked only by the thread that locked it.\"

But I have written a program wh

3条回答
  •  无人及你
    2020-12-03 00:35

    A mutex is used to prevent multiple threads from executing code that is only safe for one thread at a time.

    To do this a mutex has several features:

    1. A mutex can handle the race conditions associated with multiple threads trying to "lock" the mutex at the same time and always results with one thread winning the race.

    2. Any thread that loses the race gets put to sleep permanently until the mutex is unlocked. The mutex maintains a list of these threads.

    3. A will hand the "lock" to one and only one of the waiting threads when the mutex is unlocked by the thread who was just using it. The mutex will wake that thread.

    If that type of pattern is useful for some other purpose then go ahead and use it for a different reason.

    Back to your question. Lets say you were protecting some code from multiple thread accesses with a mutex and lets say 5 threads were waiting while thread A was executing the code. If thread B (not one of the ones waiting since they are permanently slept at the moment) unlocks the mutex, another thread will commence executing the code at the same time as thread A. Probably not desired.

    Maybe if we knew what you were thinking about using the mutex for we could give a better answer. Are you trying to unlock a mutex after a thread was canceled? Do you have code that can handle 2 threads at a time but not three and there is no mutex that lets 2 threads through at a time?

提交回复
热议问题