threadsafe2.c
903 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
char *
safe_itoa (int number, char *buf)
{
int i = 0, j;
do
{
buf[i++] = number % 10 + '0';
number /= 10;
}
while (number);
buf[i] = 0;
for (j = 0; j < i / 2; j++)
{
char c = buf[j];
buf[j] = buf[i - j - 1];
buf[i - j - 1] = c;
};
return buf;
}
void *
thread (void *param)
{
char buf[16];
int start = *((int *) (param));
int i;
printf ("Hello from thread %d\n", start);
for (i = 0; i < 10000; i++)
printf ("%d %s\n", i + start, safe_itoa (i + start, buf));
pthread_exit (param);
}
int
main (int argc, char *argv[])
{
pthread_t t1, t2;
pthread_attr_t attr;
int a, b;
void *retval;
a = 0;
pthread_attr_init (&attr);
pthread_create (&t1, &attr, thread, &a);
if (argc > 1)
{
b = 10000;
pthread_create (&t2, &attr, thread, &b);
pthread_join (t2, &retval);
};
pthread_join (t1, &retval);
exit (0);
}