-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread-4.cpp
43 lines (37 loc) · 853 Bytes
/
thread-4.cpp
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
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <stdio.h>
using namespace std;
pthread_t threads[2];
unsigned long n;
unsigned long last = 1;
int state = 0;
void *thread_func(void *threadid)
{
int tid = (long)threadid;
while (true) {
if (last >= n) {
return 0;
}
while (state == tid % 2) {
sched_yield();
}
cout << tid << " " << last << endl;
++last;
state = !state;
}
}
int main (int argc, char* argv[])
{
n = strtoul(argv[1], NULL, 10);
if (n == 1) {
cout << "1 1" << endl;
return 0;
}
pthread_create(&threads[0], NULL, thread_func, (void *)1);
pthread_create(&threads[1], NULL, thread_func, (void *)2);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
return 0;
}