-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata-pass-basic-thread.c
More file actions
34 lines (29 loc) · 863 Bytes
/
data-pass-basic-thread.c
File metadata and controls
34 lines (29 loc) · 863 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
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
// When building, you must link with the external pthread library: for example, 'gcc data-pass-basic-thread.c -lpthread'
int sum;
void *runner(void *param) {
int upper = atoi(param);
sum = 0;
for (int i = 1; i <= upper; i++) {
sum += i;
}
pthread_exit(0);
}
int main(int argc, char** argv) {
pthread_t tid; // the thread identifier
pthread_attr_t attr; // the set of thread attributes
if (argc != 2) {
fprintf(stderr, "Usage: %s <integer value>\n", argv[0]);
return -1;
}
// setting the default attributes:
pthread_attr_init(&attr);
// creating the thread:
pthread_create(&tid, &attr, runner, argv[1]);
pthread_join(tid, NULL);
printf("sum = %d\n", sum);
pthread_attr_destroy(&attr);
pthread_exit(NULL);
}