[Comparative] essays and mutex semaphore

advantage:

"Semaphore is asynchronous signal safe" (reference [2])

Disadvantages:

"I think it is not necessary semaphore synchronization primitives, because with the mutex condition variable can completely replace its function, and less prone to error ... Another problem with semaphores is that it has its own count value, usually our own data structure also has a length value, which resulted in the same information saved two "(reference [1])

"A thread can increment signal is a decreasing amount of another thread, this flexibility can lead to poor structure of the synchronous design" (Reference [2])

 in conclusion:

Semaphore applications, could be considered replaced by mutex + condition variable.

Semaphore concurrent programming like the "goto" in general, but it does a simple interface, easy call.

------------------------------------------

Further, their correct a wrong idea: the signal value of an amount of 1 equivalent to the mutex.

Only you need to write a single hands-on producer - consumer single demo can understand.

Example 1:

1  // encoding thread 
2  thread_encode () {
 . 3    of sem_wait (& task_assigned); // blocked waiting tasks 
. 4    encode ();
 . 5    sem_post (& task_done);  // notify task completion 
6  }
 7  // task thread 
. 8  thread_main () {
 . 9    of sem_wait (& task_done);  // blocked waiting for completion of the task 
10    send_data_if_has ();
 . 11    New_Task ();
 12 is    sem_post (& task_assigned); // issued notification task 
13 is  }
 14 sem_init (& task_done, 0 , . 1 );// initial state, "task completed" 
15 sem_init (& task_assigned, 0 , 0 ); // no new allocation of tasks

Comparative Example 2

 1 // 编码线程
 2 thread_encode(){
 3     pthread_mutex_lock(&mutex);
 4   encode();
 5     pthread_mutex_unlock(&mutex);
 6 }
 7 // 任务线程
 8 thread_encode(){
 9     pthread_mutex_lock(&mutex);
10   send_data_if_has();
11   new_task();
12   pthread_mutex_unlock(&mutex);
13 }

the difference

 

 

reference

[1] "Linux multi-threaded server-side programming," Thread Synchronization Essentials Chapter 2.3 to read and write do not use locks and semaphores

[2] "Linux Programming Manual" P907 POSIX Pthreads mutex semaphore in comparison

 

Guess you like

Origin www.cnblogs.com/i-am-normal/p/11710788.html