Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
ace9d8cf2c25a959a5900ca7802e11ec0c6e744b
[simgrid.git] / src / s4u / s4u_mailbox.cpp
1 /* Copyright (c) 2006-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 "xbt/log.h"
8 #include "src/msg/msg_private.h"
9
10 #include "simgrid/s4u/mailbox.hpp"
11
12 XBT_LOG_EXTERNAL_CATEGORY(s4u);
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(s4u_channel,s4u,"S4U Communication Mailboxes");
14
15
16 using namespace simgrid;
17
18 boost::unordered_map <std::string, s4u::Mailbox *> *s4u::Mailbox::mailboxes = new boost::unordered_map<std::string, s4u::Mailbox*> ();
19
20
21 s4u::Mailbox::Mailbox(const char*name, smx_mailbox_t inferior) {
22   inferior_ = inferior;
23   name_ = name;
24   mailboxes->insert({name, this});
25 }
26 const char *s4u::Mailbox::getName() {
27   return name_.c_str();
28 }
29 s4u::Mailbox *s4u::Mailbox::byName(const char*name) {
30   s4u::Mailbox *res;
31   try {
32     res = mailboxes->at(name);
33   } catch (std::out_of_range& e) {
34     // FIXME: there is a potential race condition here where two actors run Mailbox::byName on a non-existent mailbox
35     // during the same scheduling round. Both will be interrupted in the simcall creating the underlying simix mbox.
36     // Only one simix object will be created, but two S4U objects will be created.
37     // Only one S4U object will be stored in the hashmap and used, and the other one will be leaked.
38     new Mailbox(name,simcall_mbox_create(name));
39     res = mailboxes->at(name); // Use the stored one, even if it's not the one I created myself.
40   }
41   return res;
42 }
43
44 bool s4u::Mailbox::empty() {
45   return nullptr == simcall_mbox_get_head(inferior_);
46 }
47
48 void s4u::Mailbox::setReceiver(smx_process_t process) {
49   simcall_mbox_set_receiver(inferior_, process);
50 }
51 smx_process_t s4u::Mailbox::receiver() {
52   return simcall_mbox_get_receiver(inferior_);
53 }
54
55 /*------- C functions -------*/
56
57 sg_mbox_t sg_mbox_by_name(const char*name){
58   return s4u::Mailbox::byName(name);
59 }
60 int sg_mbox_is_empty(sg_mbox_t mbox) {
61   return mbox->empty();
62 }
63 void sg_mbox_setReceiver(sg_mbox_t mbox, smx_process_t process) {
64   mbox->setReceiver(process);
65 }
66 smx_process_t sg_mbox_receiver(sg_mbox_t mbox) {
67   return mbox->receiver();
68 }