]> AND Private Git Repository - loba.git/blob - msg_thread.cpp
Logo AND Algorithmique Numérique Distribuée

Private GIT Repository
API change in SimGrid 3.8: MSG_global_init -> MSG_init.
[loba.git] / msg_thread.cpp
1 #include <stdexcept>
2 #include <xbt/log.h>
3
4 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(thrd);
5
6 #include "misc.h"
7 #include "msg_thread.h"
8
9 msg_thread::msg_thread()
10     : started(false)
11     , thread(NULL)
12     , thread_name("msg_thread")
13 {
14 }
15
16 msg_thread::msg_thread(const char* name)
17     : started(false)
18     , thread(NULL)
19     , thread_name(name)
20 {
21 }
22
23 msg_thread::~msg_thread()
24 {
25     if (thread)
26         xbt_die("ERROR: trying to destroy running thread");
27 }
28
29 void msg_thread::start()
30 {
31     mutex.acquire();
32     if (started)
33         xbt_die("ERROR: thread was already started");
34     XBT_DEBUG("launch \"%s\"", thread_name.c_str());
35     thread = MSG_process_create(thread_name.c_str(),
36                                 msg_thread::start_wrapper,
37                                 this, MSG_host_self());
38     started = true;
39     mutex.release();
40 }
41
42 void msg_thread::wait()
43 {
44     mutex.acquire();
45     if (!started)
46         xbt_die("ERROR: trying to wait for a thread that was not started");
47     while (thread) {
48         XBT_DEBUG("waiting for \"%s\" to terminate",
49                   thread_name.c_str());
50         cond.wait(mutex);
51     }
52     mutex.release();
53 }
54
55 int msg_thread::start_wrapper(int, char* [])
56 {
57     msg_thread* self;
58     self = static_cast<msg_thread*>(MSG_process_get_data(MSG_process_self()));
59     XBT_DEBUG("\"%s\" started", self->thread_name.c_str());
60     self->run();
61
62     XBT_DEBUG("terminate \"%s\"", self->thread_name.c_str());
63     self->mutex.acquire();
64     self->thread = NULL;
65     self->cond.signal();
66     self->mutex.release();
67     return 0;
68 }