【发布时间】:2013-02-28 08:45:47
【问题描述】:
我可以使用pthread_create 生成一个线程并在其中安全地使用std::mutex 吗?
我认为如果 std::mutex 被实现为 pthread_mutex_t 那就没问题了,但我在任何地方都没有看到这一点
例如:
#include <pthread.h>
#include <mutex>
namespace {
std::mutex global_lock;
}
void* thread_func(void* vp) {
// std::mutex used in thread spawned with pthread_create
std::lock_guard<std::mutex> guard(global_lock);
// critical section
return nullptr;
}
int main() {
pthread_t tid;
pthread_create(&tid, nullptr, thread_func, nullptr);
pthread_join(tid, NULL);
}
顺便说一句,我正在运行 Debian Wheezy。
【问题讨论】:
-
生成线程和锁定互斥锁是两个独立的概念。您的问题实际上是关于混合来自 STL 和 PThread 的并发控制,还是特别是这一个实例?
-
@sixlettervariables 的一般混合控制。
-
您能详细说明一下需求/用例吗?您是否需要从 C API 中运行代码?对于这种情况,这可能没问题(因为使用 pthread 运行的 C API 需要基于 pthread 的 C++ 实现)。
-
@g-makulik 我不确定我是否明白你在问什么。我的特定用例并不像我关心的那样多,因为它们是否可以在一般情况下混合使用。我不打算使用任何 C API。让我们一直假设 C++11。