线程同步之互斥量加锁解锁
与互斥锁相关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);
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。
案例:创建互斥锁,锁住需要执行的线程,结束前不会被打扰
参考代码:
#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);
// 返回:若成功返回0,否则返回错误编号----创建线程
pthread_mutex_t mutex;//创建锁(互斥量)
void *func1(void*arg)//参数3:调用无类型指针API
{
pthread_mutex_lock(&mutex);//加锁
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
//pthread_self():返回自身线程id,为pthread_t类型
printf("t1:param is %d:\n",*((int*)arg));//转化为int*,再取值
pthread_mutex_unlock(&mutex);//解锁
}
void *func2(void*arg)//参数3:调用无类型指针API
{
pthread_mutex_lock(&mutex);//加锁
printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
//pthread_self():返回自身线程id,为pthread_t类型
printf("t2:param is %d:\n",*((int*)arg));//转化为int*,再取值
pthread_mutex_unlock(&mutex);//解锁
}
int main()
{
int ret;//返回值
pthread_t t1;
pthread_t t2;
//int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);//互斥锁初始化
pthread_mutex_init(&mutex,NULL);//参数2:锁的属性
int param=100;//参数4:调用时:将int*转化为void*.100:随便给的数
ret=pthread_create(&t1,NULL,func1,(void*)¶m);
//参数1:指针指向t1,NULL:线程属性,参数3:启动线程调用的函数,参数4:打印的值
ret=pthread_create(&t2,NULL,func2,(void*)¶m);
if(ret==0)
{
printf("main函数创建线程t1成功\n");
}
if(ret==0)
{
printf("main函数创建线程t2成功\n");
}
printf("main:%ld\n",(unsigned long)pthread_self());
pthread_join(t1,NULL);//等待线程
pthread_join(t2,NULL);//等待线程
pthread_mutex_destroy(&mutex);//销毁这把锁
return 0;
}
运行结果:
dazai@dazai:~$ gcc demo3.c -lpthread
dazai@dazai:~$ ./a.out
main函数创建线程t1成功
main函数创建线程t2成功
main:-1211169024
t1:-1211172032 thread is create
t1:param is 100:
t2:-1219564736 thread is create
t2:param is 100: