Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
abe169117cb618ba485fc940435cfc65664b77e5
[simgrid.git] / examples / msg / app-token-ring / app-token-ring.c
1 /* Copyright (c) 2008-2016. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "simgrid/msg.h"
7
8 XBT_LOG_NEW_DEFAULT_CATEGORY(msg_app_token_ring, "Messages specific for this msg example");
9
10 /* Main function of all processes used in this example */
11 static int foo(int argc, char *argv[])
12 {
13   unsigned int task_comm_size = 1000000; /* The token is 1MB long*/
14   int rank = xbt_str_parse_int(MSG_process_get_name(MSG_process_self()), "Any process of this example must have a numerical name, not %s");
15   char mailbox[256];
16   msg_task_t task = NULL;
17   XBT_ATTRIB_UNUSED int res;
18   if (rank == 0){ /* - The root (rank 0) first sends the token then waits to receive it back */
19     sprintf(mailbox, "%d", rank+1);
20     task = MSG_task_create("Token", 0, task_comm_size, NULL);
21     XBT_INFO("Host \"%d\" send '%s' to Host \"%s\"", rank, task->name,mailbox);
22     MSG_task_send(task, mailbox);
23     task = NULL;
24     res = MSG_task_receive(&(task), MSG_process_get_name(MSG_process_self()));
25     xbt_assert(res == MSG_OK, "MSG_task_get failed");
26     XBT_INFO("Host \"%d\" received \"%s\"", rank, MSG_task_get_name(task));
27     MSG_task_destroy(task);
28   } else{ /* - The others receive from their left neighbor (rank-1) and send to their right neighbor (rank+1) */
29     res = MSG_task_receive(&(task), MSG_process_get_name(MSG_process_self()));
30     xbt_assert(res == MSG_OK, "MSG_task_get failed");
31     XBT_INFO("Host \"%d\" received \"%s\"",rank, MSG_task_get_name(task));
32
33     if(rank+1 == MSG_get_host_number()) /* - Except for the last one which sends the token back to rank 0 */
34       sprintf(mailbox, "0");
35     else
36       sprintf(mailbox, "%d", rank+1);
37     XBT_INFO("Host \"%d\" send '%s' to Host \"%s\"",rank,task->name,mailbox);
38     MSG_task_send(task, mailbox);
39   }
40   return 0;
41 }
42
43 int main(int argc, char *argv[])
44 {
45   unsigned int i;
46   MSG_init(&argc, argv);
47   MSG_create_environment(argv[1]);       /* - Load the platform description */
48   xbt_dynar_t hosts = MSG_hosts_as_dynar();
49   msg_host_t h;
50
51   XBT_INFO("Number of host '%d'",MSG_get_host_number());
52   xbt_dynar_foreach (hosts, i, h){      /* - Give a unique rank to each host and create a @ref foo process on each */
53     char* name_host = bprintf("%u",i);
54     MSG_process_create(name_host, foo, NULL, h);
55     free(name_host);
56   }
57   xbt_dynar_free(&hosts);
58
59   int res = MSG_main();                 /* - Run the simulation */
60   XBT_INFO("Simulation time %g", MSG_get_clock());
61   return res != MSG_OK;
62 }