我有这样一个类
class ThreadPool
{
public:
ThreadPool();
ThreadPool(int total_thread);
~ThreadPool();
void active_pool(void);
void* thread_start_routine(void* run_data);
private:
int total_thread_;
queue<TASK*> task_queue;
sem_t* task_queue_mutex_;//Same function as mutex semaphore in P-C problem.
sem_t* task_queue_full_;//Same function as full semaphore in P-C problem.
};
我将在 active_pool 函数中创建多个线程,每个线程入口函数都是 thread_start_routine。
我的问题是,如果每个线程都必须使用队列 task_queue 进行 push/pop,所有线程会看到相同的队列还是他们看到的每个队列只是通过线程创建的本地拷贝
谢谢~
最佳答案
所有线程都将看到相同的队列。这就是并发编程的美妙之处。 (如果您希望每个线程有不同的实例,您可以使用 thread_local
存储持续时间 - 这是自 C++11 以来对 C++ 的新增功能。)
通常,您需要确保以线程安全的方式使用相关成员。为此使用原子类型(std::atomic
来自 C++11)和互斥单元(std::mutex
来自 C++11)。
引用资料:
http://en.cppreference.com/w/cpp/keyword/thread_local
关于C++ 将在类中创建的线程共享同一个类变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47461083/