Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
simplify some msg examples
[simgrid.git] / examples / msg / token_ring / ring_call.c
1 /* Copyright (c) 2008-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 "simgrid/msg.h"
8
9 XBT_LOG_NEW_DEFAULT_CATEGORY(ring, "Messages specific for this msg example");
10
11 /** @addtogroup MSG_examples
12  * 
13  *  @section MSG_ex_apps Examples of full applications
14  * 
15  * - <b>token_ring/ring_call.c</b>: Classical token ring communication, where a token is exchanged along a ring to
16  *   reach every participant.
17  */
18
19 static int host(int argc, char *argv[])
20 {
21   unsigned int task_comp_size = 50000000;
22   unsigned int task_comm_size = 1000000;
23   int host_number =
24           xbt_str_parse_int(MSG_process_get_name(MSG_process_self()), "Process name must be an integer but is: %s");
25   char mailbox[256];
26   msg_task_t task = NULL;
27   XBT_ATTRIB_UNUSED int res;
28   if (host_number == 0){ //master  send then receive
29     sprintf(mailbox, "%d", host_number+1);
30     task = MSG_task_create("Token", task_comp_size, task_comm_size, NULL);
31     XBT_INFO("Host \"%d\" send '%s' to Host \"%s\"",host_number,task->name,mailbox);
32     MSG_task_send(task, mailbox);
33     task = NULL;
34     res = MSG_task_receive(&(task), MSG_process_get_name(MSG_process_self()));
35     xbt_assert(res == MSG_OK, "MSG_task_get failed");
36     XBT_INFO("Host \"%d\" received \"%s\"",host_number, MSG_task_get_name(task));
37     MSG_task_destroy(task);
38   } else{ //slave receive then send
39     res = MSG_task_receive(&(task), MSG_process_get_name(MSG_process_self()));
40     xbt_assert(res == MSG_OK, "MSG_task_get failed");
41     XBT_INFO("Host \"%d\" received \"%s\"",host_number, MSG_task_get_name(task));
42
43     if(host_number+1 == MSG_get_host_number())
44       sprintf(mailbox, "0");
45     else
46       sprintf(mailbox, "%d", host_number+1);
47     XBT_INFO("Host \"%d\" send '%s' to Host \"%s\"",host_number,task->name,mailbox);
48     MSG_task_send(task, mailbox);
49   }
50   return 0;
51 }
52
53 int main(int argc, char **argv)
54 {
55   unsigned int i;
56   MSG_init(&argc, argv);
57   MSG_create_environment(argv[1]);
58   xbt_dynar_t hosts = MSG_hosts_as_dynar();
59   msg_host_t h;
60   MSG_function_register("host", host);
61
62   XBT_INFO("Number of host '%d'",MSG_get_host_number());
63   xbt_dynar_foreach (hosts, i, h){
64     char* name_host = bprintf("%u",i);
65     MSG_process_create(name_host, host, NULL, h);
66     free(name_host);
67   }
68   xbt_dynar_free(&hosts);
69
70   int res = MSG_main();
71   XBT_INFO("Simulation time %g", MSG_get_clock());
72   return res != MSG_OK;
73 }