#include <stdio.h> #include <stdlib.h> #include <pthread.h> pthread_mutex_t mutex; //定義一個互斥量 int x; //定義一個全局變量 //這是線程1的入口函數(shù) void threaddeal1(void) { while(x>0) //如果X>0 { pthread_mutex_lock(&mutex); //對互斥量進行加鎖操作 printf("線程1正在運行: x=%d \n",x); //輸出當前的x值 x--; //將x的值-1 pthread_mutex_unlock(&mutex); //對互斥兩進行開鎖操作 sleep(1); //休眠1秒 } pthread_exit(NULL); //進程退出 } //這是線程2的入口函數(shù),線程2和線程1的操作完全相同 void threaddeal2(void) { while(x>0) { pthread_mutex_lock(&mutex); printf("線程2正在運行: x=%d \n",x); x--; pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(NULL); } //這是主函數(shù) int main(int argc,char *argv[]) { pthread_t threadid1,threadid2; int ret; ret = pthread_mutex_init(&mutex,NULL); //初始化互斥鎖 if(ret != 0) { printf ("初始化互斥鎖失敗.\n"); exit (1); } x = 10; //給全局變量賦初始化值 ret = pthread_create(&threadid1, NULL, (void *)&threaddeal1, NULL); //創(chuàng)建線程1 if(ret != 0) { printf ("創(chuàng)建線程1失敗.\n"); exit (1); } ret = pthread_create(&threadid2, NULL, (void *)&threaddeal2, NULL); //創(chuàng)建線程2 if(ret != 0) { printf ("創(chuàng)建線程2失敗.\n"); exit (1); } pthread_join(threadid1, NULL); pthread_join(threadid2, NULL); //阻塞線程1和線程2 return (0); }
名稱欄目:[Linux線程]線程的同步--使用互斥鎖完成線程同步
路徑分享:http://chinadenli.net/article44/gphphe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站建設(shè)、用戶體驗、標簽優(yōu)化、電子商務(wù)、微信公眾號、全網(wǎng)營銷推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)