与互斥锁相关API
互斥量(mutex)从本质上来说是一把锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。对互斥量进行加锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变为可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。【描述的不太好】
互斥变量用 pthread_mutex_t 数据类型表示。在使用互斥变量前必须对它进行初始化,可以把它置为常量PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态地分配互斥量(例如通过调用malloc函数),那么在释放内存前需要调用pthread_mutex_destroy。
1. 创建及销毁互斥锁
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); //初始化互斥量,默认属性attr参数可以设置为NULL。
int pthread_mutex_destroy(pthread_mutex_t mutex); //释放互斥量
// 返回:若成功返回0,否则返回错误编号
要用默认的属性初始化互斥量,只需把attr设置为NULL。
2. 加锁及解锁
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex); //加锁
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex); //解锁
// 返回:若成功返回0,否则返回错误编号
如果线程不希望被阻塞,它可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果调用pthread_mutex_trylock时互斥量处于未锁住状态,那么pthread_mutex_trylock将锁住互斥量,不会出现阻塞并返回0,否则pthread_mutex_trylock就会失败,不能锁住互斥量,而返回EBUSY。
代码demo :
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr,
// void *(*start_rtn)(void *), void *restrict arg);
pthread_mutex_t mutex; //定义互斥量
void *func1(void *arg)
{
int i;
pthread_mutex_lock(&mutex); //加锁
for(i=0;i<5;i++){
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
printf("t1:param is %d\n",*((int *)arg));
sleep(1);
}
pthread_mutex_unlock(&mutex); //解锁
}
void *func2(void *arg)
{
pthread_mutex_lock(&mutex);
printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
printf("t2:param is %d\n",*((int *)arg));
pthread_mutex_unlock(&mutex);
}
void *func3(void *arg)
{
pthread_mutex_lock(&mutex);
printf("t3:%ld thread is create\n",(unsigned long)pthread_self());
printf("t3:param is %d\n",*((int *)arg));
pthread_mutex_unlock(&mutex);
}
int main()
{
int ret;
int arg = 100;
pthread_t t1;
pthread_t t2;
pthread_t t3;
//初始化互斥量
pthread_mutex_init(&mutex,NULL);
//创建 t1 线程
ret = pthread_create(&t1,NULL,func1,(void *)&arg);
if(ret == 0){
printf("main:create t1 success\n");
}
ret = pthread_create(&t2,NULL,func2,(void *)&arg);
if(ret == 0){
printf("main:create t2 success\n");
}
ret = pthread_create(&t3,NULL,func3,(void *)&arg);
if(ret == 0){
printf("main:create t3 success\n");
}
printf("main:%ld\n",(unsigned long)pthread_self());
//线程等待
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
//销毁互斥量
pthread_mutex_destroy(&mutex);
return 0;
}
不管t1、t2、t3 哪个线程先抢到锁运行 ,当t1 线程抢到锁之后都会执行完整个for循环,才会到 t2 和 t3 线程争夺运行
至于为什么main 也会在t1 运行过程中穿插进来? 那是因为main 函数并没有加锁。它不需要像t2 或 t3 那样需要等待 t1 运行完解锁之后,才能运行。