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

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 class\n";

        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 class\n";

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

通常我们在同一个 class 中声明条件变量和互斥锁,因为我们将它们用于控制、调度和优先处理线程。我认为我们不需要全局声明条件和互斥体。但是如果你真的需要,你可以在这里使用命名空间。