dongyukun
2025-02-21 2bf209dce77d2a8236dbeb14e110e300acc45452
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
#pragma once
#include"cstring"
#include<fstream>
#include<iostream>
#include<string>
#include<stdio.h>
#include <Windows.h>  
#include "Python.h"
 
#include <thread>
 
 
/*全局解释和线程锁*/
class PyGILThreadLock
{
public:
    PyGILThreadLock()
    {
        _save = NULL;
        nStatus = 0;
        nStatus = PyGILState_Check();   //检测当前线程是否拥有GIL
        //PyGILState_STATE gstate;
        if (!nStatus)
        {
            cout << "申请获取GIL" << endl;
            gstate = PyGILState_Ensure();   //如果没有GIL,则申请获取GIL
            nStatus = 1;
        }
        _save = PyEval_SaveThread();
        PyEval_RestoreThread(_save);
    }
    ~PyGILThreadLock()
    {
        _save = PyEval_SaveThread();
        PyEval_RestoreThread(_save);
        if (nStatus)
        {
            cout << "释放当前线程的GIL" << endl;
            PyGILState_Release(gstate);    //释放当前线程的GIL
        }
    }
 
private:
    PyGILState_STATE gstate;
    PyThreadState *_save;
    int nStatus;
};