-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpthread_cond_t3.cpp
More file actions
87 lines (78 loc) · 2.08 KB
/
pthread_cond_t3.cpp
File metadata and controls
87 lines (78 loc) · 2.08 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
79
80
81
82
83
84
85
86
87
#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 taxi_cond = PTHREAD_COND_INITIALIZER; //taix arrive cond
pthread_mutex_t taxi_mutex = PTHREAD_MUTEX_INITIALIZER; // sync mutex
int traveler_num = 0;
void *traveler_arrive(void *name)
{
cout << "Traveler:" << (char *)name << " needs a taxi now!" << endl;
pthread_mutex_lock(&taxi_mutex);
traveler_num++;
pthread_cond_wait(&taxi_cond, &taxi_mutex);
pthread_mutex_unlock(&taxi_mutex);
cout << "Traveler:" << (char *)name << " now got a taxi!" << endl;
pthread_exit((void *)0);
}
void *taxi_arrive(void *name)
{
cout << "Taxi:" << (char *)name << " arriver." << endl;
while (1)
{
pthread_mutex_lock(&taxi_mutex);
if (traveler_num > 0)
{
pthread_cond_signal(&taxi_cond);
pthread_mutex_unlock(&taxi_mutex);
break;
}
pthread_mutex_unlock(&taxi_mutex);
}
pthread_exit((void *)0);
}
int main()
{
pthread_t tids[3];
int flag;
flag = pthread_create(&tids[0], NULL, taxi_arrive, (void *)("Jack"));
if (flag)
{
cout << "pthread_create error:flag=" << flag << endl;
return flag;
}
cout << "time passing by" << endl;
sleep(1);
flag = pthread_create(&tids[1], NULL, traveler_arrive, (void *)("Susan"));
if (flag)
{
cout << "pthread_create error:flag=" << flag << endl;
return flag;
}
cout << "time passing by" << endl;
sleep(1);
flag = pthread_create(&tids[2], NULL, taxi_arrive, (void *)("Mike"));
if (flag)
{
cout << "pthread_create error:flag=" << flag << endl;
return flag;
}
cout << "time passing by" << endl;
sleep(1);
void *ans;
for (int i = 0; i < 3; i++)
{
flag = pthread_join(tids[i], &ans);
if (flag)
{
cout << "pthread_join error:flag=" << flag << endl;
return flag;
}
cout << "ans=" << ans << endl;
}
return 0;
}