-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathticket.cpp
More file actions
63 lines (57 loc) · 1.28 KB
/
ticket.cpp
File metadata and controls
63 lines (57 loc) · 1.28 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
/***
* @Author: wujing
* @Date: 2021-02-23 23:25:22
* @LastEditTime: 2021-02-23 23:25:40
* @LastEditors: wujing
* @Description:
* @FilePath: /code/CPlusPlusProject/pthread/synchronization/ticket.cpp
* @可以输入预定的版权声明、个性签名、空行等
*/
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
using namespace std;
int ticket_sum = 20;
void *sell_ticket(void *arg)
{
for (int i = 0; i < 20; i++)
{
if (ticket_sum > 0)
{
sleep(1);
cout << "sell the " << 20 - ticket_sum + 1 << "th" << endl;
ticket_sum--;
}
}
return 0;
}
int main()
{
int flag;
pthread_t tids[4];
for (int i = 0; i < 4; i++)
{
flag = pthread_create(&tids[i], NULL, &sell_ticket, NULL);
if (flag)
{
cout << "pthread create error ,flag=" << flag << endl;
return flag;
}
}
sleep(20);
void *ans;
for (int i = 0; i < 4; i++)
{
flag = pthread_join(tids[i], &ans);
if (flag)
{
cout << "tid=" << tids[i] << "join erro flag=" << flag << endl;
return flag;
}
cout << "ans=" << ans << endl;
}
return 0;
}