Linux System Programming (5)

1. When attention to the problem of using mutex

The critical area: lock and unlock intermediate code called critical section, when the lock should ensure that critical area as small as possible.

 

  

When the lock should ensure that critical area as small as possible:

   

  

2. Why be locked thread

Let me talk about what is an atomic operation:

Simulated by locked atomically: the intermediate lock and unlock the figure three lines of code, if not locked, in which three lines of code execution may lose the CPU, it is not atomic, and substitute with lock , will block waiting for other threads, not away time slice, so that three lines of code will be finished in one go, so a locking manner can be used to simulate atomic operation.

3. Deadlock

If two or more threads are blocked, the absence of external force, they will be unable to advance it, these threads have been waiting for each other, a phenomenon known as deadlock.

Note: The above code will be blocked at the second lock.

 

Note: Make a thread in a certain order to access shared resources, that all the threads are in the same order to access shared resources, are the first access A, then visit B. This will not be a deadlock.

4. The read-write lock features

 

The read-write lock usage scenarios

6. The write lock operation function

7. The read-write lock codes practice

(1) when the lock is not:

The results: you can see the emergence of data confusion

(2) when the lock:

The results: the number is small to large, there was no confusion data

8. The idea of ​​using condition variables

Note: a node list is biscuits, producers using the first interpolation node in the linked list.

9. The condition variable related functions described

  

Note: The limit of waiting for a condition variable, is that when incoming abstime parameters after time to, at this time if the thread has not yet unblocked, the thread will be unblocked.

10. The model code of producers and consumers to achieve

Producers have been inserted in the head node. Consumers have been the head node list of deleted (when the first node of the list is not NULL).

11. Use condition variables to achieve producer-consumer model

Results of the:

12. The functions associated semaphore

 

13. Semaphore achieve producer-consumer model

14. The signal producer-consumer model code amount to achieve

15. The Dining Philosophers Problem Analysis

 

Guess you like

Origin blog.csdn.net/mengyujia1234/article/details/91408315