1 /* Use a semaphore to implement mutual exclusion. */
4 #include <fcntl.h> /* O_CREAT */
7 #include <stdio.h> /* printf() */
8 #include <stdlib.h> /* exit() */
9 #include <unistd.h> /* sleep() */
11 /* Local functions declarations. */
13 static void* thread_func(void*);
16 /* Local variables. */
18 /* s_sem protects s_d3. */
21 static double s_d1; /* accessed before thread creation and in the created */
22 /* thread (not a race). */
23 static double s_d2; /* accessed in the created thread and after the join */
25 static double s_d3; /* accessed simultaneously from both threads (race). */
26 static int s_debug = 0;
27 static int s_do_printf = 0;
28 static int s_do_mutual_exclusion = 0;
31 /* Function definitions. */
33 int main(int argc, char** argv)
37 char semaphore_name[32];
39 while ((optchar = getopt(argc, argv, "dmp")) != EOF)
47 s_do_mutual_exclusion = 1;
58 * Use the ipcs and ipcrm commands to clean up named semaphores left by
59 * aborted instances of this process.
61 snprintf(semaphore_name, sizeof(semaphore_name), "drd-sem-open-test");
62 s_sem = sem_open(semaphore_name, O_CREAT, 0600, 1);
63 if (s_sem == SEM_FAILED)
65 fprintf(stderr, "Failed to create a semaphore with name %s\n",
71 * Switch to line-buffered mode, such that timing information can be
72 * obtained for each printf() call with strace.
78 printf("&s_d1 = %p; &s_d2 = %p; &s_d3 = %p\n", &s_d1, &s_d2, &s_d3);
84 pthread_create(&threadid, 0, thread_func, 0);
86 sleep(1); /* Wait until thread_func() finished. */
89 if (s_do_mutual_exclusion) sem_wait(s_sem);
91 if (s_do_mutual_exclusion) sem_post(s_sem);
94 /* Wait until the thread finished. */
95 pthread_join(threadid, 0);
96 if (s_do_printf) printf("s_d2 = %g (should be 2)\n", s_d2);
97 if (s_do_printf) printf("s_d3 = %g (should be 5)\n", s_d3);
100 sem_unlink(semaphore_name);
105 static void* thread_func(void* thread_arg)
109 printf("s_d1 = %g (should be 1)\n", s_d1);
113 if (s_do_mutual_exclusion) sem_wait(s_sem);
115 if (s_do_mutual_exclusion) sem_post(s_sem);