当线程处理不同的类时,应该在哪里声明条件变量、互斥对象

Where should the condition variables, mutexes be declared when the threads deal with different classes?

本文关键字:条件 声明 在哪里 变量 对象 处理 线程      更新时间:2023-10-16

这里我已经全局声明了所有内容。当条件变量、互斥体在不同的类之间共享时,它们应该在哪里声明?

应该遵循什么设计才能避免全球声明?

#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 );
}
}
}

通常我们在同一个类中声明条件变量和互斥,因为我们同时用于控制、调度和优先级线程。我认为我们不需要为条件和互斥对象全局声明。但是,如果您真的需要,您仍然可以在这里使用名称空间。