一、互斥锁
互斥量从本质上说就是一把锁, 提供对共享资源的保护访问。
1. 初始化:
在Linux下, 线程的互斥量数据类型是pthread_mutex_t. 在使用前, 要对它进行初始化:
对于静态分配的互斥量, 可以把它设置为PTHREAD_MUTEX_INITIALIZER,或者调用pthread_mutex_init.
对于动态分配的互斥量, 在申请内存(malloc)之后, 通过pthread_mutex_init进行初始化,并且在释放内存(free)前需要调用pthread_mutex_destroy.
原型:
int pthread_mutex_init(pthread_mutex_t *restrict mutex, constpthread_mutexattr_t *restric attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
头文件:
返回值: 成功则返回0, 出错则返回错误编号.
说明: 如果使用默认的属性初始化互斥量, 只需把attr设为NULL. 其他值在以后讲解。
2. 互斥操作:
对共享资源的访问, 要对互斥量进行加锁, 如果互斥量已经上了锁, 调用线程会阻塞, 直到互斥量被解锁.在完成了对共享资源的访问后, 要对互斥量进行解锁。
首先说一下加锁函数:
头文件:
原型:
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
返回值: 成功则返回0, 出错则返回错误编号.
说明: 具体说一下trylock函数, 这个函数是非阻塞调用模式, 也就是说, 如果互斥量没被锁住,trylock函数将把互斥量加锁, 并获得对共享资源的访问权限; 如果互斥量被锁住了,trylock函数将不会阻塞等待而直接返回EBUSY, 表示共享资源处于忙状态。
再说一下解所函数:
头文件:
原型: int pthread_mutex_unlock(pthread_mutex_t *mutex);
返回值: 成功则返回0, 出错则返回错误编号.
3. 死锁:
死锁主要发生在有多个依赖锁存在时, 会在一个线程试图以与另一个线程相反顺序锁住互斥量时发生.如何避免死锁是使用互斥量应该格外注意的东西。
总体来讲, 有几个不成文的基本原则:
对共享资源操作前一定要获得锁。
完成操作以后一定要释放锁。
尽量短时间地占用锁。
如果有多锁, 如获得顺序是ABC连环扣, 释放顺序也应该是ABC。
线程错误返回时应该释放它所获得的锁。
下面给个测试小程序进一步了解互斥,mutex互斥信号量锁住的不是一个变量,而是阻塞住一段程序。如果对一个mutex变量testlock,执行了第一次pthread_mutex_lock(testlock)之后,在unlock(testlock)之前的这段时间内,如果有其他线程也执行到了pthread_mutex_lock(testlock),这个线程就会阻塞住,直到之前的线程unlock之后才能执行,由此,实现同步,也就达到保护临界区资源的目的。
#include
#include
static pthread_mutex_t testlock;
pthread_t test_thread;
void *test()
{
pthread_mutex_lock(&testlock);
printf("thread Test() \n");
pthread_mutex_unlock(&testlock);
}
int main()
{
pthread_mutex_init(&testlock, NULL);
pthread_mutex_lock(&testlock);
printf("Main lock \n");
pthread_create(&test_thread, NULL, test, NULL);
sleep(1); //更加明显的观察到是否执行了创建线程的互斥锁
printf("Main unlock \n");
pthread_mutex_unlock(&testlock);
sleep(1);
pthread_join(test_thread,NULL);
pthread_mutex_destroy(&testlock);
return 0;
}
make
gcc -D_REENTRANT -lpthread -o test test.c
结果:
Main lock
Main unlock
thread Test()
一、练习要求
三个线程访问一个全局共享的字符串,thread1访问时会在这个字符串末尾追加'1'字符,thread2访问时会在这个字符串末尾追加'2'字符,thread3访问时会在这个字符串末尾追加'3‘字符。要求:thread1-thread2-thread3依次访问,最终字符串的内容为"123"。
二、第一阶段
在main函数中,开启这三个线程。并没有为线程访问共享数据加锁和同步。在main函数中sleep(3)来避免主线程过早地退出。
【实现代码】
[cpp] viewplain copy print ?
- #include
- #include
- #include
- #include
- #include
- #include
- char g_array[5]={'\0'};
- void*thread1(void*);
- void*thread2(void*);
- void*thread3(void*);
- int main(int argc,char**argv)
- {
- printf("[enter main ]\n");
- pthread_t tid1, tid2, tid3;
- int rc1=0, rc2=0,rc3=0;
- rc3 = pthread_create(&tid3, NULL, thread3,NULL);
- if(rc3 !=0)
- printf("%s:%d\n",__func__,strerror(rc3));
- rc2 = pthread_create(&tid2, NULL, thread2,NULL);
- if(rc2 !=0)
- printf("%s:%d\n",__func__,strerror(rc2));
- rc1 = pthread_create(&tid1, NULL, thread1,&tid2);
- if(rc1 !=0)
- printf("%s:%d\n",__func__,strerror(rc1));
- sleep(3);
- printf("[ leave main]\n");
- exit(0);
- }
- void*thread1(void*arg)
- {
- printf("[ enter thread1]\n");
- printf("thisis thread1, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- int index =strlen(g_array);
- g_array[index] = '1';
- printf("this is thread1, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- printf("[leave thread1 ]\n");
- pthread_exit(0);
- }
- void*thread2(void*arg)
- {
- printf("[enter thread2 ]\n");
- printf("this is thread2, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- int index =strlen(g_array);
- g_array[index] = '2';
- printf("thisis thread2, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- printf("[ leave thread2]\n");
- pthread_exit(0);
- }
- void*thread3(void*arg)
- {
- printf("[ enter thread3]\n");
- printf("thisis thread3, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- int index =strlen(g_array);
- g_array[index] = '3';
- printf("this is thread3, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- printf("[leave thread3 ]\n");
- pthread_exit(0);
- }
#include
#include
#include
#include
#include
#include
char g_array[5]= {'\0'};
void* thread1(void*);
void* thread2(void*);
void* thread3(void*);
int main(int argc, char** argv)
{
printf("[ enter main ]\n");
pthread_t tid1, tid2, tid3;
int rc1=0, rc2=0, rc3=0;
rc3 = pthread_create(&tid3, NULL, thread3, NULL);
if(rc3 != 0)
printf("%s: %d\n",__func__, strerror(rc3));
rc2 = pthread_create(&tid2, NULL, thread2, NULL);
if(rc2 != 0)
printf("%s: %d\n",__func__, strerror(rc2));
rc1 = pthread_create(&tid1, NULL, thread1, &tid2);
if(rc1 != 0)
printf("%s: %d\n",__func__, strerror(rc1));
sleep(3);
printf("[ leave main ]\n");
exit(0);
}
void* thread1(void* arg)
{
printf("[ enter thread1 ]\n");
printf("this is thread1, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
int index = strlen(g_array);
g_array[index] = '1';
printf("this is thread1, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
printf("[ leave thread1 ]\n");
pthread_exit(0);
}
void* thread2(void* arg)
{
printf("[ enter thread2 ]\n");
printf("this is thread2, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
int index = strlen(g_array);
g_array[index] = '2';
printf("this is thread2, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
printf("[ leave thread2 ]\n");
pthread_exit(0);
}
void* thread3(void* arg)
{
printf("[ enter thread3 ]\n");
printf("this is thread3, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
int index = strlen(g_array);
g_array[index] = '3';
printf("this is thread3, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
printf("[ leave thread3 ]\n");
pthread_exit(0);
}
【编译和运行命令】
gcc -lpthreadThreadTest_1.c
./a.out
【运行结果】
[ enter main ]
[ enter thread1 ]
[ enter thread3 ]
[ enter thread2 ]
this is thread1, g_array: , thread id is 3060820848
this is thread2, g_array: , thread id is 3069213552
this is thread2, g_array: 12, thread id is 3069213552
[ leave thread2 ]
this is thread3, g_array: 12, thread id is 3077606256
this is thread3, g_array: 123, thread id is 3077606256
[ leave thread3 ]
this is thread1, g_array: 123, thread id is 3060820848
[ leave thread1 ]
[ leave main ]
二、第二阶段
为线程访问共享数据加锁和同步:
1. thread1访问共享数据完毕后让cond1条件为真;
2. thread2等待cond1条件为真后才进行数据访问,访问数据完毕时让cond2条件为真;
3. thread3等待cond2条件为真后才进行数据访问,访问数据完毕时让cond3条件为真;
4.主线程等待cond3条件为真才退出。
注意:在对临界资源进行操作之前需要加锁,操作完再解锁。使用条件变量可以以原子方式阻塞线程,直到某个特定条件为真为止。
为什么条件变量始终与互斥锁一起使用,对条件的测试是在互斥锁(互斥)的保护下进行的呢?
因为“某个特性条件”通常是在多个线程之间共享的某个变量。互斥锁允许这个变量可以在不同的线程中设置和检测。
【实现代码】
[cpp] viewplain copy print ?
- #include
- #include
- #include
- #include
- #include
- #include
- char g_array[5]={'\0'};
- static pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER; //mutex
- static pthread_cond_t cond1= PTHREAD_COND_INITIALIZER; //cond
- static pthread_cond_t cond2= PTHREAD_COND_INITIALIZER; //cond
- static pthread_cond_t cond3=PTHREAD_COND_INITIALIZER; //cond
- static pthread_cond_tcond_main_exit= PTHREAD_COND_INITIALIZER; //cond
- void*thread1(void*);
- void*thread2(void*);
- void*thread3(void*);
- int main(int argc,char**argv)
- {
- printf("[ enter main]\n");
- pthread_t tid1, tid2, tid3;
- int rc1=0, rc2=0,rc3=0;
- rc3 = pthread_create(&tid3, NULL, thread3,NULL);
- if(rc3 !=0)
- printf("%s:%d\n",__func__,strerror(rc3));
- rc2 = pthread_create(&tid2, NULL, thread2,NULL);
- if(rc2 !=0)
- printf("%s:%d\n",__func__,strerror(rc2));
- rc1 = pthread_create(&tid1, NULL, thread1,&tid2);
- if(rc1 !=0)
- printf("%s:%d\n",__func__,strerror(rc1));
- pthread_mutex_lock(&mutex);
- pthread_cond_wait(&cond3,&mutex);
- pthread_mutex_unlock(&mutex);
- printf("[ leave main]\n");
- exit(0);
- }
- void*thread1(void*arg)
- {
- printf("[ enter thread1]\n");
- pthread_mutex_lock(&mutex);
- //printf("this is thread1, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- int index =strlen(g_array);
- sleep(5);
- if(index ==0)
- {
- g_array[index] = '1';
- }
- printf("thisis thread1, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- pthread_cond_signal(&cond1);
- pthread_mutex_unlock(&mutex);
- printf("[leave thread1 ]\n");
- pthread_exit(0);
- }
- void*thread2(void*arg)
- {
- printf("[enter thread2 ]\n");
- pthread_mutex_lock(&mutex); // why cant lock ???
- pthread_cond_wait(&cond1,&mutex);
- //printf("this is thread2, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- int index =strlen(g_array);
- sleep(3);
- if(index ==1)
- {
- g_array[index] = '2';
- }
- printf("this is thread2, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- pthread_cond_signal(&cond2);
- pthread_mutex_unlock(&mutex);
- printf("[ leave thread2]\n");
- pthread_exit(0);
- }
- void*thread3(void*arg)
- {
- printf("[ enter thread3]\n");
- pthread_mutex_lock(&mutex);
- pthread_cond_wait(&cond2,&mutex);
- //printf("this is thread3, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- int index =strlen(g_array);
- if(index ==2)
- {
- g_array[index] = '3';
- pthread_cond_signal(&cond3);
- }
- printf("thisis thread3, g_array: %s, thread id is%u\n",g_array, (unsigned int)pthread_self());
- pthread_mutex_unlock(&mutex);
- printf("[leave thread3 ]\n");
- pthread_exit(0);
- }
#include
#include
#include
#include
#include
#include
char g_array[5]= {'\0'};
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //mutex
static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; //cond
static pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; //cond
static pthread_cond_t cond3= PTHREAD_COND_INITIALIZER; //cond
static pthread_cond_t cond_main_exit= PTHREAD_COND_INITIALIZER; //cond
void* thread1(void*);
void* thread2(void*);
void* thread3(void*);
int main(int argc, char** argv)
{
printf("[ enter main ]\n");
pthread_t tid1, tid2, tid3;
int rc1=0, rc2=0, rc3=0;
rc3 = pthread_create(&tid3, NULL, thread3, NULL);
if(rc3 != 0)
printf("%s: %d\n",__func__, strerror(rc3));
rc2 = pthread_create(&tid2, NULL, thread2, NULL);
if(rc2 != 0)
printf("%s: %d\n",__func__, strerror(rc2));
rc1 = pthread_create(&tid1, NULL, thread1, &tid2);
if(rc1 != 0)
printf("%s: %d\n",__func__, strerror(rc1));
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond3, &mutex);
pthread_mutex_unlock(&mutex);
printf("[ leave main ]\n");
exit(0);
}
void* thread1(void* arg)
{
printf("[ enter thread1 ]\n");
pthread_mutex_lock(&mutex);
//printf("this is thread1, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
int index = strlen(g_array);
sleep(5);
if(index == 0)
{
g_array[index] = '1';
}
printf("this is thread1, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
printf("[ leave thread1 ]\n");
pthread_exit(0);
}
void* thread2(void* arg)
{
printf("[ enter thread2 ]\n");
pthread_mutex_lock(&mutex); // why cant lock ???
pthread_cond_wait(&cond1, &mutex);
//printf("this is thread2, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
int index = strlen(g_array);
sleep(3);
if(index == 1)
{
g_array[index] = '2';
}
printf("this is thread2, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
printf("[ leave thread2 ]\n");
pthread_exit(0);
}
void* thread3(void* arg)
{
printf("[ enter thread3 ]\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond2, &mutex);
//printf("this is thread3, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
int index = strlen(g_array);
if(index == 2)
{
g_array[index] = '3';
pthread_cond_signal(&cond3);
}
printf("this is thread3, g_array: %s, thread id is %u\n",g_array, (unsigned int)pthread_self());
pthread_mutex_unlock(&mutex);
printf("[ leave thread3 ]\n");
pthread_exit(0);
}
【运行结果】
[ enter main ]
[ enter thread3 ]
[ enter thread2 ]
[ enter thread1 ]
this is thread1, g_array: 1, thread id is 3065633680
[ leave thread1 ]
this is thread2, g_array: 12, thread id is 3076123536
[ leave thread2 ]
this is thread3, g_array: 123, thread id is 3086613392
[ leave thread3 ]
[ leave main ]