-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread4.cpp
47 lines (38 loc) · 871 Bytes
/
thread4.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
44
45
46
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define NUM_THREAD 100
void* thread_add(void* arg);
void* thread_subtraction(void* arg);
long long sum;
int main()
{
pthread_t t_id[NUM_THREAD];
int i;
for (i = 0; i < NUM_THREAD; i++) {
if (i % 2) {
pthread_create(&t_id[i], NULL, thread_add, NULL);
} else {
pthread_create(&t_id[i], NULL, thread_subtraction, NULL);
}
}
for (i = 0; i < NUM_THREAD; i++) {
pthread_join(t_id[i], NULL);
}
printf("sum is %d", sum);
}
void* thread_add(void* arg) {
int i = 0;
for (; i < 999999; i++) {
sum += i;
}
return NULL;
}
void* thread_subtraction(void* arg) {
int i = 0;
for (; i < 999999; i++) {
sum -= i;
}
return NULL;
}