fix cr/lfs and remove trailing whitespaces...
[supertux.git] / src / scripting / thread_queue.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include "thread_queue.hpp"
22 #include "squirrel_util.hpp"
23 #include "log.hpp"
24
25 namespace Scripting
26 {
27
28 ThreadQueue::ThreadQueue()
29 {
30 }
31
32 ThreadQueue::~ThreadQueue()
33 {
34 }
35
36 void
37 ThreadQueue::add(HSQUIRRELVM vm)
38 {
39   // create a weakref to the VM
40   HSQOBJECT vm_obj = vm_to_object(vm);
41   sq_pushobject(global_vm, vm_obj);
42   sq_weakref(global_vm, -1);
43
44   HSQOBJECT object;
45   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &object))) {
46     sq_pop(global_vm, 2);
47     throw SquirrelError(global_vm, "Couldn't get thread weakref from vm");
48   }
49   sq_addref(global_vm, &object);
50   threads.push_back(object);
51
52   sq_pop(global_vm, 2);
53 }
54
55 void
56 ThreadQueue::wakeup()
57 {
58   // we traverse the list in reverse orders and use indices. This should be
59   // robust for scripts that add new entries to the list while we're traversing
60   // it
61   size_t i = threads.size() - 1;
62   size_t end = (size_t) 0 - 1;
63   size_t size_begin = threads.size();
64   while(i != end) {
65     HSQOBJECT object = threads[i];
66
67     sq_pushobject(global_vm, object);
68     sq_getweakrefval(global_vm, -1);
69
70     HSQUIRRELVM scheduled_vm;
71     if(sq_gettype(global_vm, -1) == OT_THREAD &&
72             SQ_SUCCEEDED(sq_getthread(global_vm, -1, &scheduled_vm))) {
73       if(SQ_FAILED(sq_wakeupvm(scheduled_vm, SQFalse, SQFalse, SQTrue))) {
74         log_warning << "Couldn't wakeup scheduled squirrel VM" << std::endl;
75       }
76     }
77
78     sq_release(global_vm, &object);
79     sq_pop(global_vm, 1);
80     i--;
81   }
82
83   threads.erase(threads.begin(), threads.begin() + size_begin);
84 }
85
86 }