Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add more Mc Mini tests
[simgrid.git] / teshsuite / mc / mcmini / simple_semaphores_with_threads_deadlock.c
1 #include <pthread.h>
2 #include <semaphore.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5
6 int START_NUM;
7 int DEBUG = 0;
8
9 sem_t sem1, sem2;
10 pthread_t thread1, thread2;
11
12 static void * thread1_doit(void *forks_arg) {
13     sem_wait(&sem2);
14     sem_wait(&sem2);
15     if(DEBUG) printf("Thread 1: Posted to sem1\n");
16     sem_post(&sem1);
17     return NULL;
18 }
19
20 static void * thread2_doit(void *forks_arg) {
21     for( int i = 0; i < START_NUM+1; i++) {
22         if(DEBUG) printf("Thread 2: Waiting for sem1\n");
23         sem_wait(&sem1);
24     }
25     if(DEBUG) printf("Thread 2: Posted to sem2\n");
26     sem_post(&sem2);
27     return NULL;
28 }
29
30 int main(int argc, char* argv[]) {
31     if(argc != 3){
32         printf("Usage: %s START_NUM DEBUG_FLAG\n", argv[0]);
33         return 1;
34     }
35
36     START_NUM = atoi(argv[1]);
37     DEBUG = atoi(argv[2]);
38
39     sem_init(&sem1, 0, START_NUM);
40     sem_init(&sem2, 0, 1);
41
42     pthread_create(&thread1, NULL, &thread1_doit, NULL);
43     pthread_create(&thread2, NULL, &thread2_doit, NULL);
44
45     pthread_join(thread1, NULL);
46     pthread_join(thread2, NULL);
47
48     return 0;
49 }