-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpthread.cpp
More file actions
53 lines (48 loc) · 960 Bytes
/
pthread.cpp
File metadata and controls
53 lines (48 loc) · 960 Bytes
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
#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;
}