-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpthread_cond_t.cpp
More file actions
78 lines (68 loc) · 1.5 KB
/
pthread_cond_t.cpp
File metadata and controls
78 lines (68 loc) · 1.5 KB
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
/***
* @Author: wujing
* @Date: 2021-02-23 23:41:50
* @LastEditTime: 2021-02-23 23:42:00
* @LastEditors: wujing
* @Description:
* @FilePath: /code/CPlusPlusProject/pthread/sync/pthread_cond_t.cpp
* @可以输入预定的版权声明、个性签名、空行等
*/
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
using namespace std;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER; //cond
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; //mutex
int x = 10, y = 20;
void *f1(void *arg)
{
cout << "f1 start" << endl;
pthread_mutex_lock(&qlock);
while (x < y)
{
pthread_cond_wait(&qready, &qlock);
}
pthread_mutex_unlock(&qlock);
sleep(3);
cout << "f1 end" << endl;
return 0;
}
void *f2(void *arg)
{
cout << "f2 start" << endl;
pthread_mutex_lock(&qlock);
x = 20;
y = 10;
cout << "has a change,x=" << x << " y=" << y << endl;
pthread_mutex_unlock(&qlock);
if (x > y)
{
pthread_cond_signal(&qready);
}
cout << "f2 end" << endl;
return 0;
}
int main()
{
pthread_t tids[2];
int flag;
flag = pthread_create(&tids[0], NULL, f1, NULL);
if (flag)
{
cout << "pthread 1 create error " << endl;
return flag;
}
sleep(2);
flag = pthread_create(&tids[1], NULL, f2, NULL);
if (flag)
{
cout << "pthread 2 create erro " << endl;
return flag;
}
sleep(5);
return 0;
}