No deadlock, thread 2 has to take mutex 1 very carefully if it were to block Order, but thread 2 takes them out of order. In Example 4–3, thread 1 locks mutexes in the prescribed Must release its mutexes when it discovers that deadlock would otherwise be Such a situation, use pthread_mutex_trylock(). Take the mutexes in an order other than prescribed. However, this technique cannot always be used-sometimes you must Known as lock hierarchies: order the mutexes by logically assigning numbersĪlso, honor the restriction that you cannot take a mutex that is assigned n when you are holding any mutex assigned a number greater than n.
![create pthread c create pthread c](https://images0.cnblogs.com/blog/170763/201304/09114836-5c72d4d9617d4062b426ce862dc432c1.png)
Taken in a prescribed order, deadlock should not occur. Lock multiple mutexes, they do so in the same order. The best way to avoid this problem is to make sure that whenever threads Occurs when each attempts to lock the other mutex. If the two threads lock mutexes 1 and 2 respectively, then a deadlock There could be a problem if two threads attempt to claimīoth resources but lock the associated mutexes in different orders. You are using one of the resources, and then discover that the other resource You will occasionally want to access two resources at once. Reading an integer value is an atomic operation because integer is theĬommon word size on most machines. On a 32-bit architecture, a long long is really two 32-bit quantities. Mutex lock to guarantee that the 64-bit quantity count
#CREATE PTHREAD C UPDATE#
The increment_count() function uses the mutex lock simply to ensure an atomic update
![create pthread c create pthread c](https://gss0.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/3bf33a87e950352a2ba67baf5443fbf2b3118b56.jpg)
The two functions in Example 4–1 use the mutex lock for different purposes. Example 4–1 shows some code fragments with mutex locking.