-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpthread.c
executable file
·54 lines (41 loc) · 1.21 KB
/
pthread.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
#include <pthread.h>
#include <stdio.h>
#include <assert.h>
pthread_mutex_t cntr_mutex = PTHREAD_MUTEX_INITIALIZER;
long protVariable = 0L;
void *myThread(void *arg)
{
int i, ret;
for (i=0; i<10000;i++){
ret = pthread_mutex_lock(&cntr_mutex);
assert(ret==0);
protVariable ++;
ret = pthread_mutex_unlock( &cntr_mutex);
assert(ret==0);
}
pthread_exit(NULL);
}
#define MAX_THREADS 10
int main()
{
int ret, i ;
pthread_t threadIds[MAX_THREADS];
for(i=0;i< MAX_THREADS; i ++) {
ret= pthread_create(& threadIds[i], NULL, myThread, NULL);
if(ret != 0){
printf("Error creating thread %d \n", (int) threadIds[i]);
}
}
for(i=0; i< MAX_THREADS; i ++) {
printf("before join thread %d \n", (int)threadIds[i]);
ret = pthread_join(threadIds[i], NULL);
if(ret != 0)
printf("Error joining thread %d \n", (int)threadIds[i]);
printf("after join thread %d \n", (int)threadIds[i]);
}
printf("The protected variable value is %d\n", protVariable);
ret = pthread_mutex_destroy( &cntr_mutex);
if(ret != 0)
printf("Couldn't destroy the mutex \n ");
return 0;
}