1. 线程间互斥
1)通过互斥锁达到线程互斥的目的
2)互斥锁的目的是用来保证共享数据操作的完整,
3)保护临界资源,即任何时刻最多只能有一个线程能访问该资源
4)线程必须先获得互斥锁才能访问临界资源,访问完资源后释放该锁。如果无法获得锁,线程会阻塞直到获得锁为止。
2. 互斥函数
函数pthread_mutex_init()
头文件:#include<pthread.h>
函数原型:int pthread_mutex_init(pthread_mutex_t*mutex, const pthread_mutexattr_t *mutexattr)
函数参数:mutex 互斥锁
mutexattr 互斥锁的属性,如设置成NULL则为缺省(default)属性
函数返回值:成功:0
失败:返回错误码
其余4个函数
int pthread_mutex_lock(pthread_mutex_t*mutex) //上锁,若不成功则等待
int pthread_mutex_trylock(pthread_mutex_t*mutex) //上锁,若不成功则返回失败
int pthread_mutex_unlock(pthread_mutex_t*mutex) //解锁
int pthread_mutex_destroy(pthread_mutex_t*mutex) //删除互斥锁
注:互斥锁的本质是一个全局变量
示例程序:
/*************************************************************************
@Author: wanghao
@Created Time : Tue 22 May 2018 06:06:58 AMPDT
@File Name: pthead_mutex.c
@Description:
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
unsigned int count, value1, value2;
pthread_mutex_t mutex;
void *function(void *arg);
int main(int argc, const char *argv[])
{
count= 1;
pthread_ta_thread;
if(pthread_mutex_init(&mutex,NULL) < 0)
{
perror("failto mutex_init");
exit(-1);
}
if(pthread_create(&a_thread,NULL, function, NULL) < 0)
{
perror("failto pthread_create");
exit(-1);
}
while(1)
{
count++;
pthread_mutex_lock(&mutex);
value1= count;
sleep(1);
value2= count;
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_mutex_destory(&mutex);
return0;
}
void *function(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(value1== value2)
{
printf("value1= value2\n");
}
else
{
printf("value1!= value2\n");
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthead_exit(NULL);
}