Reputation: 57
I have a class like this
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.
};
And I will create multiple thread within the active_pool function and each thread entry-function is thread_start_routine.
My question is that if each have to push/pop with queue task_queue, will all threads see the same queue or each queue they see is just a local copy through thread creation
Thank you~
Upvotes: 1
Views: 961
Reputation: 234785
All threads will see the same queue. That's the beauty of concurrent programming. (You can use thread_local
storage duration if you want a different instance per thread - this is a new addition to C++ since C++11.)
Normally, you need to make sure the relevant members are used in a thread-safe manner. Atomic types (std::atomic
from C++11) and mutual exclusion units (std::mutex
from C++11) are used for that.
References:
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
Upvotes: 2