threadsafe3.c
1.05 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
60
61
62
63
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
char *
unsafe_itoa (int number)
{
static char buf[16];
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;
}
pthread_mutex_t itoa_mutex;
void *
thread (void *param)
{
int start = *((int *) (param));
int i;
printf("Hello from thread %d\n",start);
for (i = 0; i < 10000; i++)
{
pthread_mutex_lock(&itoa_mutex);
printf ("%d %s\n", i + start, unsafe_itoa (i + start));
pthread_mutex_unlock(&itoa_mutex);
}
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_mutex_init(&itoa_mutex,NULL);
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);
pthread_mutex_destroy(&itoa_mutex);
exit (0);
}