-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_threads.c
More file actions
executable file
·59 lines (52 loc) · 1.4 KB
/
simple_threads.c
File metadata and controls
executable file
·59 lines (52 loc) · 1.4 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
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#define array_size 1000000
typedef void* (*thread_f)(void *);
struct summer_data {
long long int *data;
long long int n;
};
void* thread_sum(struct summer_data* arg) {
if (arg->n==1) return (void*)arg->data[0];
pthread_t t1,t2;
struct summer_data s1 = {arg->data,arg->n/2};
struct summer_data s2 = {arg->data+arg->n/2,arg->n-arg->n/2};
pthread_create(&t1,NULL,(thread_f)thread_sum,&s1);
pthread_create(&t2,NULL,(thread_f)thread_sum,&s2);
void *r1, *r2;
pthread_join(t1,&r1);
pthread_join(t2,&r2);
return (void*)((long long int)r1+(long long int)r2);
}
void* thread_start(void *arg) {
int my_id = pthread_self();
printf("Thread #%d is starting execution...\n",my_id);
sleep(1);
printf("Thread #%d is executing...\n",my_id);
sleep(1);
printf("Thread #%d is finishing...\n",my_id);
return NULL;
}
int main() {
int i,err;
pthread_t *thread_buffer;
long long int sumarray[array_size];
for (i=0;i<array_size;++i) {
sumarray[i]=i;
}
struct summer_data s = {sumarray,array_size};
pthread_t t;
// pthread_create(&t,NULL,(thread_f)thread_sum,&s);
long long int sum;
// pthread_join(t,(void**)&sum);
// printf("The sum of the first %d naturals is %lld.\n",array_size,sum);
for (int j=0;j<10000;++j) {
sum = 0;
for (i=0;i<array_size;++i) {
sum+=sumarray[i];
}}
printf("Sum: %lld with single threads.\n",sum);
return 0;
}