-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtutorial-8NG.c
More file actions
88 lines (70 loc) · 2.31 KB
/
Copy pathtutorial-8NG.c
File metadata and controls
88 lines (70 loc) · 2.31 KB
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
84
85
86
87
88
#include <Python.h>
#include <stdio.h>
static PyObject* callback1(PyObject* self, PyObject* args)
{
char* str;
PyArg_ParseTuple(args, "s", &str);
printf("%s push event\n", str);
Py_RETURN_NONE;
}
static PyObject* callback2(PyObject* self, PyObject* args)
{
char* str;
PyArg_ParseTuple(args, "s", &str);
printf("%s blocking start\n", str);
sleep(5);
printf("%s blocking end\n", str);
Py_RETURN_NONE;
}
int main(int argc, char* argv[])
{
PyEval_InitThreads();
Py_Initialize();
PyObject* sysPath = PySys_GetObject((char*) "path");
PyList_Append(sysPath, PyString_FromString("."));
PyThreadState* save = PyEval_SaveThread();
PyObject *pCallback1Func = NULL, *pCallback2Func = NULL;
PyObject *pModule = NULL, *pClass = NULL, *pInst = NULL, *pArgs = NULL;
do
{
PyGILState_STATE state = PyGILState_Ensure();
{
PyMethodDef CFunc1 = {"callback1", callback1, METH_VARARGS, ""};
pCallback1Func = PyCFunction_New(&CFunc1, NULL);
if (pCallback1Func == NULL) break;
PyMethodDef CFunc2 = {"callback2", callback2, METH_VARARGS, ""};
pCallback2Func = PyCFunction_New(&CFunc2, NULL);
if (pCallback2Func == NULL) break;
pModule = PyImport_ImportModule("worker-callback");
if (pModule == NULL) break;
pClass = PyObject_GetAttrString(pModule, "ThreadManager");
if (pClass == NULL) break;
pArgs = Py_BuildValue("(OO)", pCallback1Func, pCallback2Func);
if (pArgs == NULL) break;
pInst = PyObject_Call(pClass, pArgs, NULL);
if (pInst == NULL) break;
PyObject_CallMethod(pInst, "start_thread", NULL);
}
PyGILState_Release(state);
for (int i = 0; i < 5; i++)
{
printf("main thread is running\n");
sleep(1);
}
state = PyGILState_Ensure();
{
PyObject_CallMethod(pInst, "stop_thread", NULL);
}
PyGILState_Release(state);
printf("finish\n");
} while (0);
PyEval_RestoreThread(save);
Py_XDECREF(pCallback1Func);
Py_XDECREF(pCallback2Func);
Py_XDECREF(pArgs);
Py_XDECREF(pInst);
Py_XDECREF(pClass);
Py_XDECREF(pModule);
Py_Finalize();
return 0;
}