函数中的四个线程
Four Threads in Function
我有4个线程应该进入相同的函数A.
- 我想允许只有两个人可以表演
- 我想等待所有四个,然后执行函数A
我应该怎么做(在C++中)?
C++中的条件变量在这里就足够了。
这应该适用于只允许两个线程同时进行:
// globals
std::condition_variable cv;
std::mutex m;
int active_runners = 0;
int FunctionA()
{
// do work
}
void ThreadFunction()
{
// enter lock and wait until we can grab one of the two runner slots
{
std::unique_lock<std::mutex> lock(m); // enter lock
while (active_runners >= 2) // evaluate the condition under a lock
{
cv.wait(); // release the lock and wait for a signal
}
active_runners++; // become one of the runners
} // release lock
FunctionA();
// on return from FunctionA, notify everyone that there's one less runner
{
std::unique_lock<std::mutex> lock(m); // enter lock
active_runners--;
cv.notify(); // wake up anyone blocked on "wait"
} // release lock
}
相关文章:
- 用于矢量处理的多个线程
- 如何在多个线程中创建 QSql数据库连接时防止名称冲突
- 如何声明由多个线程调用的 C++ DLL 的内部类,而无需导出类
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- 将 10 个线程与原子布尔值同步
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- 一个线程等待多个线程事件
- 如果在 2 个线程中使用,是否值得将size_t声明为 std::atomic?
- 餐饮哲学家问题 - 只有 2 个线程工作
- 如果两个线程相互依赖,则 cpp 线程连接应使用连接导致死锁
- std::cout 来自多个线程
- 是否需要 mutex() 来安全地同时访问具有 2 个线程的数组的不同元素?
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 多个线程可以安全地同时将相同的值写入同一变量吗?
- 将执行循环拆分为多个线程 (1-N-1-N-1..)
- 简单使用 std::atomic 在两个线程之间共享数据
- 如何在类C++中制作四个线程
- 使用OpenMP在四核系统上使用4个线程来加速问题
- 函数中的四个线程