下面给出一个小的测试程序进一步了解互斥,mutex互斥信号量锁住的不是一个变量,而是阻塞住一段程序。如果对一个mutex变量testlock执行了第一次pthread_mutex_lock(testlock)之后,在unlock(testlock)之前的这段时间内,如果有其它线程也执行到了pthread_mutex_lock(testlock),这个线程就会被阻塞住,直到之前的线程unlock之后才能执行,由此,实现同步,也就达到了保护临界区域资源的作用。

#include<stdio.h>
#include<pthread.h>

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;
}

二、条件变量:

这里主要说说, pthread_cond_wait()的用法。

条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个进程等待“条件变量的条件成立”而挂起;另一个线程使”条件成立“(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。

1、创建和注销:

条件变量和互斥锁一样,都有静态动态创建两种方式,

静态方式使用        PTHREAD_COND_INITIALIZER常量,如下:

pthread_cond_t cond PTHREAD_INITIALIZER;

动态方式使用    pthread_cond_init()函数,API定义如下:

int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr)

尽管POSIX标准中为条件变量定义了属性,但在LINUXthreads中并没有实现,因此,cond_attr值通常是NULL,且被忽略。

注销一个条件变量需要调用pthread_cond_destroy(),只有在没有线程在该条件变量上等待的时候才能注销这个条件变量,否则返回EBUSY。因为linux实现的条件变量没有分配什么资源,所以注销动作只包括检查是否有等待线程。API定义如下:

int pthread_cond_destroy(pthread_cond_t *cond);

2、等待和激发:

int pthread_cond_wait(pthread_cond_t *cond,pthread_mutex_t *mutex);

int pthread_cond_timedwait(pthread_cond_t *cond,pthread_mutex_t *mutex,const struct timespec * abstime)

 

等待条件有两种方式:无条件等待 pthread_cond_wait()和计时等待:pthread_cond_timedwait();其中计时等待方式如果在给定时刻前条件没有满足,则返回ETIMEOUT,结束等等待,其中abstime以与time()系统调用相同意义的绝对时间形式出现,0 表示格里尼治时间

 

无论哪种等待方式,都必须有一个互斥锁相配合,以防止多个线程同时请求pthread_cond_wait(),的竞争条件。,mutex互斥锁必须是普通锁或者适应锁,

且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在县城挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()时自动解锁互斥量(如同执行了pthread_unlock_mutex),并等待条件触发。这时线程挂起,不占用cpu时间,直到条件变量被触发。

因此全过程可以描述为:

(1)pthread_mutex_lock()上锁

(2)pthread_cond_wait()等待,等待过程分解为:解锁--条件满足--加锁

(3)pthread_mutex_unlock()解锁

激发条件有两种方式:pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;而pthread_cond_broadcast()则激活所有等待线程。 两者 如果没有等待的线程,则什么也不做。

下面一位童鞋问的问题解释了上面的说明:

当pthread_cond_t 调用pthread_cond_wait 进入等待状态时,pthread_mutex_t 互斥信号就无效了。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//多线程同步--条件锁(相当与windows的事件)测试 
//要先让pthread_cond_wait进入等待信号状态,才能调用pthread_cond_signal发送信号,才有效. 
//不能让pthread_cond_signal在pthread_cond_wait前面执行 
#include <stdio.h> 
#include<pthread.h> //多线程所用头文件 
#include <semaphore.h> //信号量使用头文件 
pthread_cond_t g_cond /*=PTHREAD_MUTEX_INITIALIZER*///申明条锁,并用宏进行初始化 
pthread_mutex_t g_mutex ; 
//线程执行函数 
void threadFun1(void
int i; 
pthread_mutex_lock(&g_mutex); //1 
pthread_cond_wait(&g_cond,&g_mutex); //如g_cond无信号,则阻塞 
for( i = 0;i < 2; i++ ){ 
printf("thread threadFun1.\n"); 
sleep(1); 
pthread_cond_signal(&g_cond); 
pthread_mutex_unlock(&g_mutex); 
int main(void
pthread_t id1; //线程的标识符 
pthread_t id2; 
pthread_cond_init(&g_cond,NULL); //也可以程序里面初始化 
pthread_mutex_init(&g_mutex,NULL); //互斥变量初始化 
int i,ret; 
ret = pthread_create(&id1,NULL,(void *)threadFun1, NULL); 
if ( ret!=0 ) { //不为0说明线程创建失败 
printf ("Create pthread1 error!\n"); 
exit (1); 
sleep(5); //等待子线程先开始 
pthread_mutex_lock(&g_mutex); //2 
pthread_cond_signal(&g_cond); //给个开始信号,注意这里要先等子线程进入等待状态在发信号,否则无效 
pthread_mutex_unlock(&g_mutex); 
pthread_join(id1,NULL); 
pthread_cond_destroy(&g_cond); //释放 
pthread_mutex_destroy(&g_mutex); //释放 
return 0
}

明明是1先锁了互斥变量,但是代码执行到2还是一样可以锁定,为什么会这样?

pthread_cond_wait()什么情况下才会解锁,继续跑下去,看下面:

问题解释:

    当程序进入pthread_cond_wait等待后,将会把g_mutex进行解锁,当离开pthread_cond_wait()之前,g_mutex会重新枷锁。所以在main中的g——mutex会被加锁。

看下面代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <pthread.h>   
#include <unistd.h>   
 
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;   
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;   
 
struct node {   
int n_number;   
struct node *n_next;   
} *head = NULL;   
 
/*[thread_func]*/ 
static void cleanup_handler(void *arg)   
{   
printf("Cleanup handler of second thread.\n");   
free(arg);   
(void)pthread_mutex_unlock(&mtx);   
}   
 
static void *thread_func(void *arg)   
{   
struct node *p = NULL;   
 
pthread_cleanup_push(cleanup_handler, p);   
while (1) {   
pthread_mutex_lock(&mtx);           //这个mutex主要是用来保证pthread_cond_wait的并发性  
while (head == NULL)   {               //这个while要特别说明一下,单个pthread_cond_wait功能很完善,为何这里要有一个while (head == NULL)呢?因为pthread_cond_wait里的线程可能会被意外唤醒,如果这个时候head != NULL,则不是我们想要的情况。这个时候,应该让线程继续进入pthread_cond_wait  
pthread_cond_wait(&cond, &mtx);         // pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,然后阻塞在等待对列里休眠,直到再次被唤醒(大多数情况下是等待的条件成立而被唤醒,唤醒后,该进程会先锁定先pthread_mutex_lock(&mtx);,再读取资源, 用这个流程是比较清楚的/*block-->unlock-->wait() return-->lock*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/errno.h>
#include <sys/types.h>
#include <signal.h>
#include <pthread.h>
 
#define    min(a,b)    ((a) < (b) ? (a) : (b))
#define    max(a,b)    ((a) > (b) ? (a) : (b))
 
#define    MAXNITEMS         1000000
#define    MAXNTHREADS            100
 
int        nitems;            /* read-only by producer and consumer */
struct {
pthread_mutex_t    mutex;
int    buff[MAXNITEMS];
int    nput;
int    nval;
} shared = { PTHREAD_MUTEX_INITIALIZER };
 
void    *produce(void *), *consume(void *);
 
/* include main */
int
main(int argc, char **argv)
{
int            i, nthreads, count[MAXNTHREADS];
pthread_t    tid_produce[MAXNTHREADS], tid_consume;
 
if (argc != 3) {
printf("usage: prodcons3 <#items> <#threads>\n");
return -1;
}
 
nitems = min(atoi(argv[1]), MAXNITEMS);
nthreads = min(atoi(argv[2]), MAXNTHREADS);
 
/* 4create all producers and one consumer */
 
for (i = 0; i < nthreads; i++) {
count[i] = 0;
pthread_create(&tid_produce[i], NULL, produce, &count[i]);
}
pthread_create(&tid_consume, NULL, consume, NULL);
 
/* 4wait for all producers and the consumer */
for (i = 0; i < nthreads; i++) {
pthread_join(tid_produce[i], NULL);
printf("count[%d] = %d\n", i, count[i]);   
}
pthread_join(tid_consume, NULL);
 
exit(0);
}
/* end main */
 
void *
produce(void *arg)
{
for ( ; ; ) {
pthread_mutex_lock(&shared.mutex);
if (shared.nput >= nitems) {
pthread_mutex_unlock(&shared.mutex);
return(NULL);        /* array is full, we're done */
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int *) arg) += 1;
}
}
 
/* include consume */
void
consume_wait(int i)
{
for ( ; ; ) {
pthread_mutex_lock(&shared.mutex);
if (i < shared.nput) {
pthread_mutex_unlock(&shared.mutex);
return;            /* an item is ready */
}
pthread_mutex_unlock(&shared.mutex);
}
}
 
void *
consume(void *arg)
{
int        i;
 
for (i = 0; i < nitems; i++) {
consume_wait(i);
if (shared.buff[i] != i)
printf("buff[%d] = %d\n", i, shared.buff[i]);
}
return(NULL);
}