Salome HOME
5fa391e846244fdf6f3c8a9530aff6a089f6d447
[modules/med.git] / src / MEDCalc / cmp / MEDPyLockWrapper.hxx
1 // Copyright (C) 2011-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #ifndef SRC_MEDCALC_CMP_MEDPYLOCKWRAPPER_HXX_
21 #define SRC_MEDCALC_CMP_MEDPYLOCKWRAPPER_HXX_
22
23 #include <Python.h>
24
25 #ifdef _DEBUG_
26   #include <iostream>
27 #endif
28
29 /**
30  * \class MEDPyLockWrapper
31  * \brief Python GIL wrapper. Copy of GUI's PyLockWrapper.
32  *
33  * Utility class wrapping the Python GIL acquisition. This makes use of the high level
34  * API (PyGILState_Ensure and PyGILState_Release), and is hence compatible with only
35  * one running Python interpreter (no call to Py_NewInterpreter()).
36  * When the class is instantiated the lock is acquired. It is released at destruction time.
37  * Copy construction (and hence assignation) is forbidden.
38  */
39 class MEDPyLockWrapper
40 {
41 public:
42   /**
43    * \brief Constructor. Automatically acquires GIL.
44    */
45   MEDPyLockWrapper()
46   {
47     _gil_state = PyGILState_Ensure();
48     // Save current thread state for later comparison
49     _state = PyGILState_GetThisThreadState();
50   }
51
52   /**
53    * \brief Destructor. Automatically releases GIL.
54    */
55   ~MEDPyLockWrapper()
56   {
57     PyThreadState* _currState = PyGILState_GetThisThreadState();
58 #ifdef _DEBUG_
59     if (_currState != _state)
60     {
61       std::cout << "!!!!!!!!! MEDPyLockWrapper inconsistency - now entering infinite loop for debugging\n";
62       while(1);
63     }
64 #endif
65     PyGILState_Release(_gil_state);
66   }
67
68 private:
69   PyGILState_STATE _gil_state;
70   PyThreadState* _state;
71
72   // "Rule of 3" - Forbid usage of copy operator and copy-constructor
73   MEDPyLockWrapper(const MEDPyLockWrapper & another);
74   const MEDPyLockWrapper & operator=(const MEDPyLockWrapper & another);
75 };
76 #endif /* SRC_MEDCALC_CMP_MEDPYLOCKWRAPPER_HXX_ */