当线程处理不同的类时,应该在哪里声明条件变量、互斥对象
Where should the condition variables, mutexes be declared when the threads deal with different classes?
这里我已经全局声明了所有内容。当条件变量、互斥体在不同的类之间共享时,它们应该在哪里声明?
应该遵循什么设计才能避免全球声明?
#include "thread_class.h"
#include <unistd.h>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <iostream>
// Thread_manager class: ***************************************************************************************************************
std::queue<int> queue_m;
std::mutex mutex_k;
bool watch;
std::mutex mutex_x;
std::mutex mutex_y;
std::condition_variable cv_x;
std::condition_variable cv_y;
ThreadManager::ThreadManager() : obj_thread_B_( &B::Run, &obj_class_B_),
obj_thread_A_( &A::Run, &obj_class_A_ )
{
watch = false;
}
ThreadManager::~ThreadManager()
{
obj_thread_A_.join();
obj_thread_B_.join();
}
void A::Run()
{
while( 1 )
{
std::unique_lock<std::mutex> lk( mutex_x );
while (watch == false)
cv_x.wait( lk );
std::cout << "nA classn";
someint++;
queue_m.push( someint );
cv_y.notify_all();
// some time consuming operation
for (int t = 0; t < 1000000; t++)
{
}
}
}
void B::Run()
{
while( 1 )
{
std::cout << "nB classn";
if (queue_m.size() > 0)
{
int temp = queue_m.front();
std::cout << "nTaken out: " << temp;
queue_m.pop();
cv_x.notify_all();
}
else
{
std::unique_lock<std::mutex> lk( mutex_y );
watch = true;
cv_x.notify_all();
cv_y.wait( lk );
}
}
}
通常我们在同一个类中声明条件变量和互斥,因为我们同时用于控制、调度和优先级线程。我认为我们不需要为条件和互斥对象全局声明。但是,如果您真的需要,您仍然可以在这里使用名称空间。
相关文章:
- 当线程处理不同的类时,应该在哪里声明条件变量、互斥对象
- 有条件的使用声明
- 使用 decltype 的条件声明类型
- 条件类型声明
- 类声明自己(*this)为private以避免竞争条件/放弃在gcc中对threadprivate的请求
- 将静态 const 成员重新声明为 constexpr 是否会自动使其符合内联条件
- 可以在C 11中有条件声明的朋友类
- 可以在C 03中有条件地声明朋友类吗?
- 在此作用域中未声明条件变量函数
- 如何在 if 条件中声明变量
- (C++)如何基于条件声明对象类成员
- 在 FOR 循环语句的条件部分中使用声明
- 模板类中的条件引用声明
- 比较条件中的字符串,而不将它们声明为字符串
- 在条件中使用do-while循环内部声明的变量
- 声明不能发生在条件运算符表达式内部
- if条件中的C++静态和非静态变量声明
- 条件中声明的变量的作用域
- c++编译器如何处理在条件语句中声明的类型
- c++:是否可能/建议基于运行时条件声明变量?