make compiled in python extension initialization more flexable
[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 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   }
29   // someone already started a copy of the interpreter
30   return interpreter_thread;
31 }
32
33 GuiProxy *ThreadManager::get_gui_proxy()
34 {
35   static GuiProxy *master;
36   static QThreadStorage <GuiProxy *> storage;
37   if (!master) {
38     // we don't have a master object so we probably should make one
39     assert (storage.hasLocalData() == false);
40     master = new GuiProxy;
41     if (!master) {
42       QMessageBox::critical(0, "Memory error", "Out of memory");
43     }
44     storage.setLocalData(master);
45     return master;
46   } else if (storage.hasLocalData()) {
47     // we've been initialized properly
48     return storage.localData();
49   } else {
50     // we have a master, but not a local proxy,
51     GuiProxy *client = new GuiProxy(master);
52     if (!client) {
53       QMessageBox::critical(0, "Memory error", "Out of memory");
54     }
55     storage.setLocalData(client);
56     return client;
57   }
58 }