linux中的C裡面使用pthread_mutex_t鎖

來源:互聯網
上載者:User

linux下為了多線程同步,通常用到鎖的概念。
posix下抽象了一個鎖類型的結構:ptread_mutex_t。通過對該結構的操作,來判斷資源是否可以訪問。顧名思義,加鎖(lock)後,別人就無法開啟,只有當鎖沒有關閉(unlock)的時候才能訪問資源。
它主要用如下5個函數進行操作。
1:pthread_mutex_init(pthread_mutex_t * mutex,const pthread_mutexattr_t *attr);
初始化鎖變數mutex。attr為鎖屬性,NULL值為預設屬性。
2:pthread_mutex_lock(pthread_mutex_t *mutex);加鎖
3:pthread_mutex_tylock(pthread_mutex_t *mutex);加鎖,但是與2不一樣的是當鎖已經在使用的時候,返回為EBUSY,而不是掛起等待。
4:pthread_mutex_unlock(pthread_mutex_t *mutex);釋放鎖
5:pthread_mutex_destroy(pthread_mutex_t *mutex);使用完後釋放
下面經典例子為建立兩個線程對sum從1加到100。前面第一個線程從1-49,後面從50-100。主線程讀取最後的加值。為了防止資源競爭,用了pthread_mutex_t 鎖操作。

#include<stdlib.h>#include<stdio.h>#include<unistd.h>#include<pthread.h>typedef struct ct_sum{int sum;pthread_mutex_t lock;}ct_sum;void * add1(void * cnt){           pthread_mutex_lock(&(((ct_sum*)cnt)->lock));   int i;       for( i=0;i<50;i++){       (*(ct_sum*)cnt).sum+=i;}   pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));  pthread_exit(NULL);  return 0;}void * add2(void *cnt){        int i;   cnt= (ct_sum*)cnt;   pthread_mutex_lock(&(((ct_sum*)cnt)->lock));   for( i=50;i<101;i++)   {    (*(ct_sum*)cnt).sum+=i;          }  pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));   pthread_exit(NULL);   return 0;}int main(void){ int i;pthread_t ptid1,ptid2;int sum=0;ct_sum cnt;pthread_mutex_init(&(cnt.lock),NULL);cnt.sum=0;pthread_create(&ptid1,NULL,add1,&cnt);pthread_create(&ptid2,NULL,add2,&cnt);pthread_mutex_lock(&(cnt.lock));printf("sum %d\n",cnt.sum);pthread_mutex_unlock(&(cnt.lock));pthread_join(ptid1,NULL);pthread_join(ptid2,NULL);pthread_mutex_destroy(&(cnt.lock));return 0;}  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.