-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread-demo.c
69 lines (62 loc) · 1.83 KB
/
thread-demo.c
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
60
61
62
63
64
65
66
67
68
69
// C Threading demo
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NUM_THREADS 4
void *print_hello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello world! This is thread #%ld\n", tid);
pthread_exit(NULL);
}
void *busy_work(void *t)
{
int i;
long tid;
double result = 0.0;
tid = (long)t;
printf("Thread %ld starting...\n", tid);
for (i = 0; i < 10000000; i++)
{
result = result + sin(i) * tan(i);
}
printf("Thread %ld done. | Result = %e\n", tid, result);
pthread_exit((void *) t);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
int rc;
long t;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (t = 0; t < NUM_THREADS; t++)
{
printf("Main: Creating thread %ld\n", t);
rc = pthread_create(&threads[t], &attr, busy_work, (void *)t);
if (rc)
{
printf("Error; return code from pthread_create() is %d\n", rc);
exit(-1);
}
printf("Main: Completed join with thread %ld having a status of %ld\n", t, (long)status);
}
/*
for (t = 0; t < NUM_THREADS; t++)
{
printf("In main: creating thread #%ld\n", t);
rc = pthread_create(&threads[t], NULL, print_hello, (void *)t);
if (rc)
{
printf("Error; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
*/
printf("Main: program finished.... exiting.\n");
pthread_exit(NULL);
}