-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha3multithreads_class.cpp
83 lines (75 loc) · 1.67 KB
/
a3multithreads_class.cpp
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
// Author: Baruch Sterin <[email protected]>
#include <Python.h>
#include <string>
#include <vector>
#include <thread>
using namespace std;
class SubInterpreter
{
public:
SubInterpreter()
{
PyInterpreterConfig config = {
.use_main_obmalloc = 0,
.allow_fork = 0,
.allow_exec = 0,
.allow_threads = 0,
.allow_daemon_threads = 0,
.check_multi_interp_extensions = 1,
.gil = PyInterpreterConfig_OWN_GIL,
};
Py_NewInterpreterFromConfig(&_ts, &config);
// _ts->interp->strict_extension_compat = false;
}
~SubInterpreter()
{
if (_ts)
{
Py_EndInterpreter(_ts);
}
}
void swap_to_self()
{
PyThreadState_Swap(_ts);
}
private:
PyThreadState *_ts;
};
void f(const char *tname)
{
SubInterpreter sub;
// sub.swap_to_self();
std::string code = R"PY(
print("sub_________________TNAME")
#import pickle
a = 0
for i in range(10000000):
a = a+1
print("finished")
)PY";
code.replace(code.find("TNAME"), 5, tname);
PyRun_SimpleString(code.c_str());
}
int main()
{
Py_Initialize();
PyGILState_STATE gstate = PyGILState_Ensure();
std::string code = R"PY(
import sys
print(sys.version)
print(f"TNAME Values in the array")
)PY";
code.replace(code.find("TNAME"), 5, "main_interpreter");
PyRun_SimpleString(code.c_str());
// SubInterpreter s1, s2, s3, s4;
std::thread t1{f, "t1___"};
std::thread t2{f, "t2___"};
std::thread t3{f, "t3___"};
std::thread t4{f, "t4___"};
t1.join();
t2.join();
t3.join();
t4.join();
Py_Finalize();
return 0;
}