threads2.cpp
650 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
#include <stdio.h>
#include "mutex.h"
volatile int Counter=0;
Mutex m;
void *
thread1 (void *p)
{
for (unsigned int i = 0; i < 100000; i++)
{
MutexLock l(m);
Counter++;
Counter--;
}
pthread_exit (p);
}
void *
thread2 (void *p)
{
for (unsigned int i = 0; i < 100000; i++)
{
MutexLock l(m);
Counter++;
Counter--;
}
pthread_exit (p);
}
int
main ()
{
pthread_t t1;
pthread_t t2;
pthread_create (&t1, NULL, thread1, NULL);
pthread_create (&t2, NULL, thread2, NULL);
pthread_join (t1, (void **) NULL);
pthread_join (t2, (void **) NULL);
printf ("Counter=%d\n", Counter);
}