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
第一個線程函數完了才執行第二個線程函數