線程間互斥

來源:互聯網
上載者:User

1.引入互斥(mutual exclusion)鎖的目的是用來保證共用資料操作的完整性
2.互斥鎖主要用來保護臨界資源
3.每個臨界資源都由一個互斥鎖來保護,任何時刻最多隻能有一個線程能訪問該資源
4.線程必須先獲得互斥鎖才能訪問臨界資源,訪問完資源後釋放該鎖,如果無法獲得鎖,則線程會阻塞直到獲得鎖為止
用到的函數
pthread_mutex_init();
pthread_create();
pthread_join();
pthread_mutex_lock();
pthread_mutex_unlock();
----------------------------------------------------------------------------------
common.h
-----------------------------------------------------------------------------------
#ifndef _COMMON_H
#define _COMMON_H
 #include<stdio.h>
 #include<stdlib.h>
 #include<pthread.h>
extern void pthread_function1(void *arg);
extern void pthread_function2(void *arg);
#endif
-------------------------------------------------------------------------------------
pthread_mutex.c
---------------------------------------------------------------------------------------
#include"common.h"
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
int gval;
int i;
int main(int argc,char **argv)
{
 pthread_t th1,th2;
 pthread_mutex_init(&mutex,NULL);
 pthread_create(&th1,NULL,(void *)pthread_function1,NULL);
 pthread_create(&th2,NULL,(void *)pthread_function2,NULL);
 pthread_join(th1,NULL);
 pthread_join(th2,NULL);
 return 0;
}
void pthread_function1(void *arg)
{
 for(i=0;i<5;i++)
 {
  pthread_mutex_lock(&mutex);
  gval++;
  pthread_mutex_unlock(&mutex);
  printf("thread1 NO.%d=%d/n",i,gval);
 }
}
void pthread_function2(void *arg)
{
 for(i=0;i<5;i++)
 {
  pthread_mutex_lock(&mutex);
  gval=gval+2;
  pthread_mutex_unlock(&mutex);
  printf("thread2 NO.%d=%d/n",i,gval);
 }
}
-----------------------------------------------------------------------------------
結果:
[root@localhost pthread mutex]# ./s
thread1 NO.0=1
thread1 NO.1=2
thread1 NO.2=3
thread1 NO.3=4
thread1 NO.4=5
thread2 NO.0=7
thread2 NO.1=9
thread2 NO.2=11
thread2 NO.3=13
thread2 NO.4=15
第一個線程函數完了才執行第二個線程函數

聯繫我們

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