Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
107e250d39a089e77365252f8b09102e85f77c5a
[simgrid.git] / examples / msg / synchro-semaphore / synchro-semaphore.c
1 /* Copyright (c) 2013-2019. 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 "simgrid/msg.h"
8
9 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_semaphore_example, "Messages specific for this msg example");
10
11 msg_sem_t sem;
12
13 static int peer(int argc, char* argv[]){
14   int i = 0;
15   while(i < argc) {
16     double wait_time = xbt_str_parse_double(argv[i],"Invalid wait time: %s");
17     i++;
18     MSG_process_sleep(wait_time);
19     XBT_INFO("Trying to acquire %d", i);
20     MSG_sem_acquire(sem);
21     XBT_INFO("Acquired %d", i);
22
23     wait_time = xbt_str_parse_double(argv[i], "Invalid wait time: %s");
24     i++;
25     MSG_process_sleep(wait_time);
26     XBT_INFO("Releasing %d", i);
27     MSG_sem_release(sem);
28     XBT_INFO("Released %d", i);
29   }
30   MSG_process_sleep(50);
31   XBT_INFO("Done");
32
33   return 0;
34 }
35
36 int main(int argc, char* argv[])
37 {
38   MSG_init(&argc, argv);
39   MSG_create_environment(argv[1]);
40
41   msg_host_t h = MSG_host_by_name("Fafard");
42
43   sem = MSG_sem_init(1);
44   char** aliceTimes = xbt_new(char*, 9);
45   aliceTimes[0] = xbt_strdup("0");
46   aliceTimes[1] = xbt_strdup("1");
47   aliceTimes[2] = xbt_strdup("3");
48   aliceTimes[3] = xbt_strdup("5");
49   aliceTimes[4] = xbt_strdup("1");
50   aliceTimes[5] = xbt_strdup("2");
51   aliceTimes[6] = xbt_strdup("5");
52   aliceTimes[7] = xbt_strdup("0");
53   aliceTimes[8] = NULL;
54
55   char** bobTimes = xbt_new(char*, 9);
56   bobTimes[0] = xbt_strdup("0.9");
57   bobTimes[1] = xbt_strdup("1");
58   bobTimes[2] = xbt_strdup("1");
59   bobTimes[3] = xbt_strdup("2");
60   bobTimes[4] = xbt_strdup("2");
61   bobTimes[5] = xbt_strdup("0");
62   bobTimes[6] = xbt_strdup("0");
63   bobTimes[7] = xbt_strdup("5");
64   bobTimes[8] = NULL;
65
66   MSG_process_create_with_arguments("Alice", peer, NULL, h, 8, aliceTimes);
67   MSG_process_create_with_arguments("Bob", peer, NULL, h, 8, bobTimes);
68
69   msg_error_t res = MSG_main();
70   MSG_sem_destroy(sem);
71   XBT_INFO("Finished\n");
72   return (res != MSG_OK);
73 }