[Linux線程]線程的同步--使用互斥鎖完成線程同步

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_mutex_t mutex;    //定義一個(gè)互斥量             
int x;                    //定義一個(gè)全局變量                                
//這是線程1的入口函數(shù)
void threaddeal1(void)                
{
  while(x>0)              //如果X>0
  {
    pthread_mutex_lock(&mutex);        //對(duì)互斥量進(jìn)行加鎖操作       
    printf("線程1正在運(yùn)行: x=%d \n",x); //輸出當(dāng)前的x值
    x--;                                //將x的值-1
    pthread_mutex_unlock(&mutex);       //對(duì)互斥兩進(jìn)行開鎖操作
    sleep(1);                           //休眠1秒
  }
  pthread_exit(NULL);                   //進(jìn)程退出
}
//這是線程2的入口函數(shù),線程2和線程1的操作完全相同
void threaddeal2(void) 
{
  while(x>0)
  {
    pthread_mutex_lock(&mutex); 
    printf("線程2正在運(yùn)行: 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://muchs.cn/article44/gphphe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站建設(shè)、用戶體驗(yàn)標(biāo)簽優(yōu)化、電子商務(wù)、微信公眾號(hào)全網(wǎng)營(yíng)銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)