Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright notices
[simgrid.git] / examples / msg / semaphores / synchro.c
1 /* Copyright (c) 2013-2015. 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 #include "simgrid/msg.h"
10 #include "xbt/log.h"
11
12 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_semaphore_example,
13                              "Messages specific for this msg example");
14
15 msg_sem_t sem;
16
17 static int peer(int argc, char* argv[]){
18
19   int i = 0; 
20   
21   while(i < argc) {
22     double wait_time = atof(argv[i++]);
23     MSG_process_sleep(wait_time);
24     XBT_INFO("Trying to acquire %d", i);
25     MSG_sem_acquire(sem);
26     XBT_INFO("Acquired %d", i);
27
28     wait_time = atof(argv[i++]);
29     MSG_process_sleep(wait_time);
30     XBT_INFO("Releasing %d", i);
31     MSG_sem_release(sem);
32     XBT_INFO("Released %d", i);
33   }
34   MSG_process_sleep(50);
35   XBT_INFO("Done");
36
37   return 0;
38 }
39
40 int main(int argc, char* argv[]) {
41
42   MSG_init(&argc, argv);
43   MSG_create_environment(argv[1]);
44   
45   xbt_dynar_t hosts = MSG_hosts_as_dynar();
46   msg_host_t h = xbt_dynar_get_as(hosts,0,msg_host_t);
47
48   sem = MSG_sem_init(1);
49   char** aliceTimes = xbt_new(char*, 9);
50   int nbAlice = 0;
51   aliceTimes[nbAlice++] = xbt_strdup("0"); 
52   aliceTimes[nbAlice++] = xbt_strdup("1");
53   aliceTimes[nbAlice++] = xbt_strdup("3");
54   aliceTimes[nbAlice++] = xbt_strdup("5");
55   aliceTimes[nbAlice++] = xbt_strdup("1");
56   aliceTimes[nbAlice++] = xbt_strdup("2");
57   aliceTimes[nbAlice++] = xbt_strdup("5");
58   aliceTimes[nbAlice++] = xbt_strdup("0");
59   aliceTimes[nbAlice++] = NULL;
60
61   char** bobTimes = xbt_new(char*, 9);
62   int nbBob = 0;
63   bobTimes[nbBob++] = xbt_strdup("0.9"); 
64   bobTimes[nbBob++] = xbt_strdup("1");
65   bobTimes[nbBob++] = xbt_strdup("1");
66   bobTimes[nbBob++] = xbt_strdup("2");
67   bobTimes[nbBob++] = xbt_strdup("2");
68   bobTimes[nbBob++] = xbt_strdup("0");
69   bobTimes[nbBob++] = xbt_strdup("0");
70   bobTimes[nbBob++] = xbt_strdup("5");
71   bobTimes[nbBob++] = NULL;
72  
73
74   MSG_process_create_with_arguments(xbt_strdup("Alice"), peer, NULL, 
75                                     h, 8, aliceTimes);
76   MSG_process_create_with_arguments(xbt_strdup("Bob"), peer, NULL, 
77                                     h, 8, bobTimes);
78
79   msg_error_t res = MSG_main();
80   printf("Finished\n");
81   return (res != MSG_OK);
82 }