Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Rename directory.
[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,"Messages specific for this sem example");
15
16
17
18 #define THREAD_THREADS_MAX                      ((unsigned int)10)
19
20 /*
21  * the thread funtion.
22  */
23 void*
24 thread_routine(void* param);
25
26 /* an entry of the table of threads */
27 typedef struct s_thread_entry
28 {
29         xbt_os_thread_t thread;
30         unsigned int thread_index;      /* the index of the thread      */
31 }s_thread_entry_t,* thread_entry_t;
32
33
34 static xbt_os_sem_t 
35 sem = NULL;
36
37 static
38 int value = 0;
39 int
40 main(int argc, char* argv[])
41 {
42         s_thread_entry_t threads_table[THREAD_THREADS_MAX] = {0};       
43         unsigned int i,j;
44         int exit_code = 0;
45         
46         xbt_init(&argc,argv);
47         
48         sem = xbt_os_sem_init(1);
49         
50         i = 0;
51         
52         while(i < THREAD_THREADS_MAX)
53         {
54                 threads_table[i].thread_index = i;
55
56                 if(NULL == (threads_table[i].thread = xbt_os_thread_create("thread",thread_routine,&(threads_table[i].thread_index))))
57                         break;
58         
59                 i++;
60         }
61         
62         /* close the thread handles */
63         for(j = 0; j < THREAD_THREADS_MAX; j++)
64                 xbt_os_thread_join(threads_table[j].thread,NULL);
65         
66         xbt_os_sem_destroy(sem);
67         
68         INFO1("sem_basic terminated with exit code %d (success)",EXIT_SUCCESS);
69
70         return EXIT_SUCCESS;
71                 
72 }
73
74 void*
75 thread_routine(void* param)
76 {
77         int thread_index = *((int*)param);
78         int exit_code = 0;
79         
80         xbt_os_sem_acquire(sem);
81         INFO1("Hello i'm the thread %d",thread_index);
82         value++;
83         INFO1("The new value of the global variable is %d, bye",value);
84         xbt_os_sem_release(sem);
85         
86         xbt_os_thread_exit(&exit_code);
87
88         return (void*)(NULL);
89 }
90
91
92