77// Blog article: http://mateusz.loskot.net/?p=2819
88
99#include " Redirector.hpp"
10+ #include " gil.hpp"
1011
1112#pragma warning(disable: 4127) // conditional expression is constant
1213#pragma warning(disable: 4068) // gcc pragma warnings
@@ -30,6 +31,7 @@ struct Stdout
3031
3132static PyObject* Stdout_write (PyObject* self, PyObject* args)
3233{
34+ gil_scoped_acquire acquire;
3335 std::size_t written (0 );
3436 Stdout* selfimpl = reinterpret_cast <Stdout*>(self);
3537 if (selfimpl->write )
@@ -48,6 +50,7 @@ static PyObject* Stdout_write(PyObject* self, PyObject* args)
4850
4951static PyObject* Stdout_flush (PyObject* self, PyObject* /* args*/ )
5052{
53+ gil_scoped_acquire acquire;
5154 Stdout *selfimpl = reinterpret_cast <Stdout *>(self);
5255 if (selfimpl->flush )
5356 {
@@ -151,9 +154,12 @@ static struct PyModuleDef redirectordef = {
151154
152155PyObject* Redirector::init ()
153156{
157+ gil_scoped_acquire acquire;
154158 StdoutType.tp_new = PyType_GenericNew;
155159 if (PyType_Ready (&StdoutType) < 0 )
160+ {
156161 return NULL ;
162+ }
157163 PyObject* m = PyModule_Create (&redirectordef);
158164 if (m)
159165 {
@@ -171,6 +177,8 @@ PyObject* Redirector::init()
171177
172178void Redirector::set_stdout (std::ostream* ostr)
173179{
180+ gil_scoped_acquire acquire;
181+
174182 stdout_write_type writeFunc = [ostr](std::string msg) { *ostr << msg; };
175183 stdout_flush_type flushFunc = [ostr]{ ostr->flush (); };
176184
@@ -180,6 +188,8 @@ void Redirector::set_stdout(std::ostream* ostr)
180188
181189void Redirector::set_stdout (stdout_write_type write, stdout_flush_type flush)
182190{
191+ gil_scoped_acquire acquire;
192+
183193 if (!m_stdout)
184194 {
185195 m_stdout_saved =
@@ -196,11 +206,15 @@ void Redirector::set_stdout(stdout_write_type write, stdout_flush_type flush)
196206
197207void Redirector::reset_stdout ()
198208{
209+ PyGILState_STATE gstate;
210+ gstate = PyGILState_Ensure ();
211+
199212 if (m_stdout_saved)
200213 PySys_SetObject (const_cast <char *>(" stdout" ), m_stdout_saved);
201214
202215 Py_XDECREF (m_stdout);
203216 m_stdout = 0 ;
217+ PyGILState_Release (gstate);
204218}
205219
206220} // namespace plang
0 commit comments