提交 | 用户 | 时间
|
b2ff26
|
1 |
#pragma once |
D |
2 |
#include"cstring" |
|
3 |
#include<fstream> |
|
4 |
#include<iostream> |
|
5 |
#include<string> |
|
6 |
#include<stdio.h> |
|
7 |
#include <Windows.h> |
|
8 |
#include "Python.h" |
|
9 |
|
|
10 |
#include <thread> |
|
11 |
|
|
12 |
|
|
13 |
/*全局解释和线程锁*/ |
|
14 |
class PyGILThreadLock |
|
15 |
{ |
|
16 |
public: |
|
17 |
PyGILThreadLock() |
|
18 |
{ |
|
19 |
_save = NULL; |
|
20 |
nStatus = 0; |
|
21 |
nStatus = PyGILState_Check(); //检测当前线程是否拥有GIL |
|
22 |
//PyGILState_STATE gstate; |
|
23 |
if (!nStatus) |
|
24 |
{ |
|
25 |
cout << "申请获取GIL" << endl; |
|
26 |
gstate = PyGILState_Ensure(); //如果没有GIL,则申请获取GIL |
|
27 |
nStatus = 1; |
|
28 |
} |
|
29 |
_save = PyEval_SaveThread(); |
|
30 |
PyEval_RestoreThread(_save); |
|
31 |
} |
|
32 |
~PyGILThreadLock() |
|
33 |
{ |
|
34 |
_save = PyEval_SaveThread(); |
|
35 |
PyEval_RestoreThread(_save); |
|
36 |
if (nStatus) |
|
37 |
{ |
|
38 |
cout << "释放当前线程的GIL" << endl; |
|
39 |
PyGILState_Release(gstate); //释放当前线程的GIL |
|
40 |
} |
|
41 |
} |
|
42 |
|
|
43 |
private: |
|
44 |
PyGILState_STATE gstate; |
|
45 |
PyThreadState *_save; |
|
46 |
int nStatus; |
|
47 |
}; |