在上一篇文章中已經用訊號量來實現線程間的互斥,達到了互斥鎖的效果,今天這篇文章將講述怎樣用訊號量去實現同步。
訊號量的互斥同步都是通過PV原語來操作的,我們可以通過註冊兩個訊號量,讓它們在互斥的問題上互動,從而達到同步。通過下面執行個體就可以很容易理解:
#include <stdlib.h><br />#include <stdio.h><br />#include <unistd.h><br />#include <pthread.h><br />#include <semaphore.h><br />#include <errno.h> </p><p>#define return_if_fail(p) if((p) == 0){printf ("[%s]:func error!/n", __func__);return;} </p><p>typedef struct _PrivInfo<br />{<br /> sem_t s1;<br /> sem_t s2;<br /> time_t end_time;<br />}PrivInfo; </p><p>static void info_init (PrivInfo* thiz);<br />static void info_destroy (PrivInfo* thiz);<br />static void* pthread_func_1 (PrivInfo* thiz);<br />static void* pthread_func_2 (PrivInfo* thiz); </p><p>int main (int argc, char** argv)<br />{<br /> pthread_t pt_1 = 0;<br /> pthread_t pt_2 = 0;<br /> int ret = 0;<br /> PrivInfo* thiz = NULL; </p><p> thiz = (PrivInfo* )malloc (sizeof (PrivInfo));<br /> if (thiz == NULL)<br /> {<br /> printf ("[%s]: Failed to malloc priv./n");<br /> return -1;<br /> } </p><p> info_init (thiz); </p><p> ret = pthread_create (&pt_1, NULL, (void*)pthread_func_1, thiz);<br /> if (ret != 0)<br /> {<br /> perror ("pthread_1_create:");<br /> } </p><p> ret = pthread_create (&pt_2, NULL, (void*)pthread_func_2, thiz);<br /> if (ret != 0)<br /> {<br /> perror ("pthread_2_create:");<br /> } </p><p> pthread_join (pt_1, NULL);<br /> pthread_join (pt_2, NULL); </p><p> info_destroy (thiz); </p><p> return 0;<br />} </p><p>static void info_init (PrivInfo* thiz)<br />{<br /> return_if_fail (thiz != NULL); </p><p> thiz->end_time = time(NULL) + 10; </p><p> sem_init (&thiz->s1, 0, 1);<br /> sem_init (&thiz->s2, 0, 0); </p><p> return;<br />} </p><p>static void info_destroy (PrivInfo* thiz)<br />{<br /> return_if_fail (thiz != NULL); </p><p> sem_destroy (&thiz->s1);<br /> sem_destroy (&thiz->s2); </p><p> free (thiz);<br /> thiz = NULL; </p><p> return;<br />} </p><p>static void* pthread_func_1 (PrivInfo* thiz)<br />{<br /> return_if_fail (thiz != NULL); </p><p> while (time(NULL) < thiz->end_time)<br /> {<br /> sem_wait (&thiz->s2);<br /> printf ("pthread1: pthread1 get the lock./n"); </p><p> sem_post (&thiz->s1);<br /> printf ("pthread1: pthread1 unlock/n"); </p><p> sleep (1);<br /> } </p><p> return;<br />} </p><p>static void* pthread_func_2 (PrivInfo* thiz)<br />{<br /> return_if_fail (thiz != NULL); </p><p> while (time (NULL) < thiz->end_time)<br /> {<br /> sem_wait (&thiz->s1);<br /> printf ("pthread2: pthread2 get the unlock./n"); </p><p> sem_post (&thiz->s2);<br /> printf ("pthread2: pthread2 unlock./n"); </p><p> sleep (1);<br /> } </p><p> return;<br />}<br />
通過執行結果後,可以看出,會先執行線程二的函數,然後再執行線程一的函數。它們兩就實現了同步。在上大學的時候,雖然對這些概念知道,可都沒有實踐過,所以有時候時間一久就會模糊甚至忘記,到了工作如果還保持這麼一種狀態,那就太可怕了。雖然現在外面的技術在不斷的變化更新,可是不管怎麼變,其核心技術還是依舊的,所以我們必須要打好自己的基礎,再學習其他新的知識,那時候再學新的知識也會覺得比較簡單的。閑話多說了兩句,在下一篇文章中,我們將會實現一個經典的執行個體回顧這段時間對多線程的學習,那就是消費者和生產者。
~~END~~