概念
互斥量(mutex)从本质上来说是一把锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。对互斥量进行加锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变为可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。
用法
第一步全局定义一个pthread_mutex_t类型
pthread_mutex_t mutex;
第二步在主函数创建及销毁互斥锁
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号
第三步* 在相对应的线程需要操作的位置加锁及解锁*
int pthread_mutex_lock(pthread_mutex_t mutex);
int pthread_mutex_unlock(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号
例子:
如果不加锁的话两个线程间会争夺资源,互相输出
加锁后会运行完锁内的任务并且解锁才会执行其他线程的任务
运行的目的:使得fun1得到3就退出
#include<stdio.h>
#include<pthread.h>
int data = 0;
pthread_mutex_t mutex;
void *fun1(void *arg){
printf("t1: %ld thread\n",(unsigned long)pthread_self());//将其id输出
printf("param1 : %d\n",*((int *)arg));
pthread_mutex_lock(&mutex);
while(1){
printf("t1: %d\n",data++);
sleep(1);
if (data == 3){
pthread_mutex_unlock(&mutex);
printf("=====t1 quit======\n");
break;
}
}
}
void *fun2(void *arg){
printf("t2: %ld thread\n",(unsigned long)pthread_self());//将其id输出
printf("param2 : %d\n",*((int *)arg));
while(1){
pthread_mutex_lock(&mutex);
printf("t2: %d\n",data++);
sleep(1);
pthread_mutex_unlock(&mutex);
}
}
int main(){
int ret;
int param = 100;
pthread_mutex_init(&mutex,NULL);
pthread_t t1;
pthread_t t2;
char *pret = NULL;
ret = pthread_create(&t1,NULL,fun1,(void *)¶m);//创建线程
ret = pthread_create(&t2,NULL,fun2,(void *)¶m);
printf("main: %ld thread\n",(unsigned long)pthread_self());
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}