8abf2149e0b5ef1e55351128c633bf0e93d5bec5
[mussa.git] / qui / threading / ThreadManager.cpp
1 #include "qui/threading/ThreadManager.hpp"
2 #include "qui/threading/InterpreterThread.hpp"
3 #include <QMessageBox>
4 #include <QMutex>
5 #include <QThreadStorage>
6
7 ThreadManager& ThreadManagerFactory() {
8   static ThreadManager *mgr;
9   if (!mgr) {
10     mgr = new ThreadManager;
11   }
12   return *mgr;
13 }
14
15 ThreadManager::ThreadManager()
16 {
17   // initialize thread variable
18   get_gui_proxy();
19 }
20
21 const InterpreterThread *ThreadManager::create_interpreter() {
22   
23   static QMutex interpreter_lock;
24   static InterpreterThread *interpreter_thread;
25   if (interpreter_lock.tryLock()) {
26     // we're the first thread
27     interpreter_thread = new InterpreterThread();
28     interpreter_thread->start();
29   }
30   return interpreter_thread;
31   // someone already started a copy of the interpreter
32 }
33
34 GuiProxy *ThreadManager::get_gui_proxy()
35 {
36   static GuiProxy *master;
37   static QThreadStorage <GuiProxy *> storage;
38   if (!master) {
39     // we don't have a master object so we probably should make one
40     assert (storage.hasLocalData() == false);
41     master = new GuiProxy;
42     if (!master) {
43       QMessageBox::critical(0, "Memory error", "Out of memory");
44     }
45     storage.setLocalData(master);
46     return master;
47   } else if (storage.hasLocalData()) {
48     // we've been initialized properly
49     return storage.localData();
50   } else {
51     // we have a master, but not a local proxy,
52     GuiProxy *client = new GuiProxy(master);
53     if (!client) {
54       QMessageBox::critical(0, "Memory error", "Out of memory");
55     }
56     storage.setLocalData(client);
57     return client;
58   }
59 }