線程同步與互斥:互斥鎖

來源:互聯網
上載者:User

線程同步與互斥:互斥鎖
為什麼需要互斥鎖?

在多任務作業系統中,同時啟動並執行多個任務可能都需要使用同一種資源。這個過程有點類似於,公司部門裡,我在使用著印表機列印東西的同時(還沒有列印完),別人剛好也在此刻使用印表機列印東西,如果不做任何處理的話,列印出來的東西肯定是錯亂的。

 

下面我們用程式類比一下這個過程,線程一需要列印“ hello ”,線程二需要列印“ world ”,不加任何處理的話,列印出來的內容會錯亂:

 

[cpp] view plaincopy

  1. #include
  2. #include
  3. #include
  4.  
  5. // 印表機
  6. void printer(char *str)
  7. {
  8. while(*str!='\0')
  9. {
  10. putchar(*str);
  11. fflush(stdout);
  12. str++;
  13. sleep(1);
  14. }
  15. printf("\n");
  16. }
  17.  
  18. // 線程一
  19. void *thread_fun_1(void *arg)
  20. {
  21. char *str = "hello";
  22. printer(str); //列印
  23. }
  24.  
  25. // 線程二
  26. void *thread_fun_2(void *arg)
  27. {
  28. char *str = "world";
  29. printer(str); //列印
  30. }
  31.  
  32. int main(void)
  33. {
  34. pthread_t tid1, tid2;
  35.  
  36. // 建立 2 個線程
  37. pthread_create(&tid1, NULL, thread_fun_1, NULL);
  38. pthread_create(&tid2, NULL, thread_fun_2, NULL);
  39.  
  40. // 等待線程結束,回收其資源
  41. pthread_join(tid1, NULL);
  42. pthread_join(tid2, NULL);
  43.  
  44. return 0;
  45. }
    運行結果如下:

     

     

    實際上,印表機是有做處理的,我在列印著的時候別人是不允許列印的,只有等我列印結束後別人才允許列印。這個過程有點類似於,把印表機放在一個房間裡,給這個房間安把鎖,這個鎖預設是開啟的。當 A 需要列印時,他先過來檢查這把鎖有沒有鎖著,沒有的話就進去,同時上鎖在房間裡列印。而在這時,剛好 B 也需要列印,B 同樣先檢查鎖,發現鎖是鎖住的,他就在門外等著。而當 A 列印結束後,他會開鎖出來,這時候 B 才進去上鎖列印。

     

    而線上程裡也有這麼一把鎖——互斥鎖(mutex),互斥鎖是一種簡單的加鎖的方法來控制對共用資源的訪問,互斥鎖只有兩種狀態,即上鎖( lock )和解鎖( unlock )。

     

    互斥鎖的操作流程如下:

    1)在訪問共用資源後臨界地區前,對互斥鎖進行加鎖。

    2)在訪問完成後釋放互斥鎖導上的鎖。

    3)對互斥鎖進行加鎖後,任何其他試圖再次對互斥鎖加鎖的線程將會被阻塞,直到鎖被釋放。

     

    互斥鎖的資料類型是: pthread_mutex_t。

     

    互斥鎖基本操作

    以下函數需要的標頭檔:

    #include

     

    1)初始化互斥鎖

    int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);

    功能:

    初始化一個互斥鎖。

    參數:

    mutex:互斥鎖地址。類型是 pthread_mutex_t 。
    attr:設定互斥量的屬性,通常可採用預設屬性,即可將 attr 設為 NULL。

     

    可以使用宏 PTHREAD_MUTEX_INITIALIZER 靜態初始化互斥鎖,比如:
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    這種方法等價於使用 NULL 指定的 attr 參數調用 pthread_mutex_init() 來完成動態初始化,不同之處在於 PTHREAD_MUTEX_INITIALIZER 宏不進行錯誤檢查。

    傳回值:

    成功:0,成功申請的鎖預設是開啟的。

    失敗:非 0 錯誤碼

     

    2)上鎖

    int pthread_mutex_lock(pthread_mutex_t *mutex);

    功能:

    對互斥鎖上鎖,若互斥鎖已經上鎖,則調用者一直阻塞,直到互斥鎖解鎖後再上鎖。

    參數:

    mutex:互斥鎖地址。

    傳回值:

    成功:0

    失敗:非 0 錯誤碼

     

    int pthread_mutex_trylock(pthread_mutex_t *mutex);

    調用該函數時,若互斥鎖未加鎖,則上鎖,返回 0;若互斥鎖已加鎖,則函數直接返回失敗,即 EBUSY。

     

    3)解鎖

    int pthread_mutex_unlock(pthread_mutex_t * mutex);

    功能:

    對指定的互斥鎖解鎖。

    參數:

    mutex:互斥鎖地址。

    傳回值:

    成功:0

    失敗:非 0 錯誤碼

     

    4)銷毀互斥鎖

    int pthread_mutex_destroy(pthread_mutex_t *mutex);

    功能:

    銷毀指定的一個互斥鎖。互斥鎖在使用完畢後,必須要對互斥鎖進行銷毀,以釋放資源。

    參數:

    mutex:互斥鎖地址。

    傳回值:

    成功:0

    失敗:非 0 錯誤碼

     

    互斥鎖應用執行個體

    我們通過互斥鎖完善上面的例子,範例程式碼如下:

     

    [cpp] view plaincopy
    1. #include
    2. #include
    3. #include
    4.  
    5. pthread_mutex_t mutex; //互斥鎖
    6.  
    7. // 印表機
    8. void printer(char *str)
    9. {
    10. pthread_mutex_lock(&mutex); //上鎖
    11. while(*str!='\0')
    12. {
    13. putchar(*str);
    14. fflush(stdout);
    15. str++;
    16. sleep(1);
    17. }
    18. printf("\n");
    19. pthread_mutex_unlock(&mutex); //解鎖
    20. }
    21.  
    22. // 線程一
    23. void *thread_fun_1(void *arg)
    24. {
    25. char *str = "hello";
    26. printer(str); //列印
    27. }
    28.  
    29. // 線程二
    30. void *thread_fun_2(void *arg)
    31. {
    32. char *str = "world";
    33. printer(str); //列印
    34. }
    35.  
    36. int main(void)
    37. {
    38. pthread_t tid1, tid2;
    39.  
    40. pthread_mutex_init(&mutex, NULL); //初始化互斥鎖
    41.  
    42. // 建立 2 個線程
    43. pthread_create(&tid1, NULL, thread_fun_1, NULL);
    44. pthread_create(&tid2, NULL, thread_fun_2, NULL);
    45.  
    46. // 等待線程結束,回收其資源
    47. pthread_join(tid1, NULL);
    48. pthread_join(tid2, NULL);
    49.  
    50. pthread_mutex_destroy(&mutex); //銷毀互斥鎖
    51.  
    52. return 0;
    53. }

       


      運行結果如下:

       

       

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.