歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux 多線程同步(信號量)

Linux 多線程同步(信號量)

日期:2017/3/1 10:09:32   编辑:Linux編程

sem_wait函數也是一個原子操作,它的作用是從信號量的值減去一個“1”,但它永遠會先等待該信號量為一個非零值才開始做減法。也就是說,如果你對一個值為2的信號量調用sem_wait(),線程將會繼續執行,這信號量的值將減到1。如果對一個值為0的信號量調用sem_wait(),這個函數就 會地等待直到有其它線程增加了這個值使它不再是0為止。如果有兩個線程都在sem_wait()中等待同一個信號量變成非零值,那麼當它被第三個線程增加 一個“1”時,等待線程中只有一個能夠對信號量做減法並繼續執行,另一個還將處於等待狀態。

sem_post函數的作用是給信號量的值加上一個“1”,它是一個“原子操作”---即同時對同一個信號量做加“1”操作的兩個線程是不會沖突的;而同 時對同一個文件進行讀、加和寫操作的兩個程序就有可能會引起沖突。信號量的值永遠會正確地加一個“2”--因為有兩個線程試圖改變它。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <semaphore.h>
  6. int myglobal;
  7. sem_t sem;
  8. void * thread_function(void *arg)
  9. {
  10. int i,j;
  11. for (i = 0; i < 10; i += 1)
  12. {
  13. sem_wait(&sem);
  14. j = myglobal;
  15. j = j+1;
  16. printf(".");
  17. fflush(stdout);
  18. sleep(1);
  19. myglobal = j;
  20. sem_post(&sem);
  21. }
  22. return NULL;
  23. }
  24. int main(void)
  25. {
  26. pthread_t mythread;
  27. int i;
  28. sem_init(&sem, 0, 1);//信號量初始化
  29. if(pthread_create(&mythread, NULL, thread_function, NULL))
  30. {
  31. printf("create thread error!\n");
  32. abort();
  33. }
  34. /* sleep(1);*/
  35. for(i = 0; i < 10; i++)
  36. {
  37. sem_wait(&sem);//=0
  38. myglobal = myglobal + 1;
  39. printf("o");
  40. fflush(stdout);
  41. sleep(1);
  42. sem_post(&sem);//=1
  43. }
  44. if(pthread_join(mythread, NULL))
  45. {
  46. printf("waiting thread failed!\n");
  47. abort();
  48. }
  49. printf("myglobal equals %d\n",myglobal);
  50. exit(0);
  51. }
Copyright © Linux教程網 All Rights Reserved