C++ 将在类中创建的线程共享同一个类变量吗?

标签 c++ multithreading pthreads

我有这样一个类

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

http://en.cppreference.com/w/cpp/atomic/atomic

http://en.cppreference.com/w/cpp/thread/mutex

关于C++ 将在类中创建的线程共享同一个类变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47461083/

相关文章:

linux - 什么时候调用 pthread_attr_destroy 是安全的?

c - Larry, Moe, Curly 互斥

c++ - 使用模板时,如何解决以下编译器错误,以实现程序所需的行为?

c# - 尽管是try/catch,但是异常会结束线程吗?

android - 什么是 E/AbstractTracker : Can't create handler inside thread that has not called Looper. prepare()?

c# - 为什么这些任务在同一个线程中启动?

c - Pthreads 在旧的 ARM Linux 上是否以相同的方式处理?

c++ - 如何使用C++中带有不可复制成员的initializer_list创建映射?

c++ - 将 Fortran 用户定义类型转换为 C++ 类

c++ - 前向声明中的字段类型不完整