Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use binary dir for bindir, and cd to home dir.
[simgrid.git] / examples / xbt / sem_basic.c
1 /* Copyright (c) 2007. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9
10
11 #include "xbt/xbt_os_thread.h"
12 #include "xbt.h"
13 #include "xbt/log.h"
14 XBT_LOG_NEW_DEFAULT_CATEGORY(sem_basic,
15                              "Messages specific for this sem example");
16
17
18
19 #define THREAD_THREADS_MAX      ((unsigned int)10)
20
21 /*
22  * the thread funtion.
23  */
24 void *thread_routine(void *param);
25
26 /* an entry of the table of threads */
27 typedef struct s_thread_entry {
28   xbt_os_thread_t thread;
29   unsigned int thread_index;    /* the index of the thread      */
30 } s_thread_entry_t, *thread_entry_t;
31
32
33 static xbt_os_sem_t sem = NULL;
34
35 static
36 int value = 0;
37 int main(int argc, char *argv[])
38 {
39   s_thread_entry_t threads_table[THREAD_THREADS_MAX] = { 0 };
40   unsigned int i, j;
41   int exit_code = 0;
42
43   xbt_init(&argc, argv);
44
45   sem = xbt_os_sem_init(1);
46
47   i = 0;
48
49   while (i < THREAD_THREADS_MAX) {
50     threads_table[i].thread_index = i;
51
52     if (NULL ==
53         (threads_table[i].thread =
54          xbt_os_thread_create("thread", thread_routine,
55                               &(threads_table[i].thread_index))))
56       break;
57
58     i++;
59   }
60
61   /* close the thread handles */
62   for (j = 0; j < THREAD_THREADS_MAX; j++)
63     xbt_os_thread_join(threads_table[j].thread, NULL);
64
65   xbt_os_sem_destroy(sem);
66
67   XBT_INFO("sem_basic terminated with exit code %d (success)", EXIT_SUCCESS);
68
69   return EXIT_SUCCESS;
70
71 }
72
73 void *thread_routine(void *param)
74 {
75   int thread_index = *((int *) param);
76   int exit_code = 0;
77
78   xbt_os_sem_acquire(sem);
79   XBT_INFO("Hello i'm the thread %d", thread_index);
80   value++;
81   XBT_INFO("The new value of the global variable is %d, bye", value);
82   xbt_os_sem_release(sem);
83
84   xbt_os_thread_exit(&exit_code);
85
86   return (void *) (NULL);
87 }