1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//
#include <Thread.h>
using namespace std;
using namespace IcePy;
IcePy::AllowThreads::AllowThreads()
{
_state = PyEval_SaveThread();
}
IcePy::AllowThreads::~AllowThreads()
{
PyEval_RestoreThread(_state);
}
IcePy::AdoptThread::AdoptThread()
{
_state = PyGILState_Ensure();
}
IcePy::AdoptThread::~AdoptThread()
{
PyGILState_Release(_state);
}
IcePy::ThreadHook::ThreadHook(PyObject* threadNotification, PyObject* threadStart, PyObject* threadStop) :
_threadNotification(threadNotification), _threadStart(threadStart), _threadStop(threadStop)
{
if(threadNotification)
{
if(!PyObject_HasAttrString(threadNotification, STRCAST("start")) ||
!PyObject_HasAttrString(threadNotification, STRCAST("stop")))
{
throw Ice::InitializationException(__FILE__, __LINE__,
"threadNotification object must have 'start' and 'stop' methods");
}
}
if(threadStart && !PyCallable_Check(threadStart))
{
throw Ice::InitializationException(__FILE__, __LINE__, "threadStart must be a callable");
}
if(threadStop && !PyCallable_Check(threadStop))
{
throw Ice::InitializationException(__FILE__, __LINE__, "threadStop must be a callable");
}
Py_XINCREF(threadNotification);
Py_XINCREF(threadStart);
Py_XINCREF(threadStop);
}
void
IcePy::ThreadHook::start()
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
if(_threadNotification.get())
{
PyObjectHandle tmp = PyObject_CallMethod(_threadNotification.get(), STRCAST("start"), 0);
if(!tmp.get())
{
throwPythonException();
}
}
if(_threadStart.get())
{
PyObjectHandle args = PyTuple_New(0);
PyObjectHandle tmp = PyObject_Call(_threadStart.get(), args.get(), 0);
if(!tmp.get())
{
throwPythonException();
}
}
}
void
IcePy::ThreadHook::stop()
{
AdoptThread adoptThread; // Ensure the current thread is able to call into Python.
if(_threadNotification.get())
{
PyObjectHandle tmp = PyObject_CallMethod(_threadNotification.get(), STRCAST("stop"), 0);
if(!tmp.get())
{
throwPythonException();
}
}
if(_threadStop.get())
{
PyObjectHandle args = PyTuple_New(0);
PyObjectHandle tmp = PyObject_Call(_threadStop.get(), args.get(), 0);
if(!tmp.get())
{
throwPythonException();
}
}
}
|