【发布时间】:2018-01-02 13:27:17
【问题描述】:
我有一些代码应该是线程安全的 python/c++ api。我正在使用宏Py_BEGIN_ALLOW_THREADS 和Py_END_ALLOW_THREADS,它们展开以创建保存线程状态并创建锁。我在方法退出之前释放锁;一次在 if 语句范围内,一次在方法范围内。
为什么不能编译?它会在第二个 Py_END_ALLOW_THREADS 宏处生成错误:error: _save was not declared in this scope。
uint8_t SerialBuffer::push_msg() {
#if defined (UBUNTU)
Py_BEGIN_ALLOW_THREADS
#endif
if (_type == ARRAY) {
// array access
} else if (_type == PRIORITY_QUEUE) {
// queue access
} else {
// Placing the return statement in the preprocessor directive
// has no effect.
#if defined (UBUNTU)
Py_END_ALLOW_THREADS
#endif
return FAIL;
}
#if defined (UBUNTU)
Py_END_ALLOW_THREADS
#endif
return SUCCESS;
}
我还尝试将return 语句放在#if 指令范围内,这会产生相同的错误。但是,这是可行的:
uint8_t SerialBuffer::push_msg() {
#if defined (UBUNTU)
Py_BEGIN_ALLOW_THREADS
#endif
if (_type == ARRAY) {
// array access
} else if (_type == PRIORITY_QUEUE) {
// queue access
} else {
// NOTE lack of #if directive here.
// Even though if this code executes the code below will not.
// Seems like a relatively simple problem for lambda calculus, no?
return FAIL;
}
#if defined (UBUNTU)
Py_END_ALLOW_THREADS
#endif
return SUCCESS;
}
编辑:我知道第二个示例不进行线程清理;但是,它可以编译。
编辑2:
Py_BEGIN_ALLOW_THREADS 扩展为 { PyThreadState *_save; _save = PyEval_SaveThread();
Py_END_ALLOW_THREADS 扩展为 PyEval_RestoreThread(_save); }
注意在BEGIN 前面和END 前面的范围括号。为什么宏扩展包含范围是合乎逻辑的选择?
【问题讨论】:
标签: python c++ multithreading macros c-preprocessor