I want to use two queues where the 1st queue will push the data to the queue and the 2nd thread will remove the data from the queue. Can somebody help me plz on implementing this in VC++?
I am new to the threads and queue.
I want to use two queues where the 1st queue will push the data to the queue and the 2nd thread will remove the data from the queue. Can somebody help me plz on implementing this in VC++?
I am new to the threads and queue.
This is the producer / consumer problem, here is one implementation of it in c++
Here is a few pointers and some sample code:
std::queue<int> data; // the queue
boost::mutex access; // a mutex for synchronising access to the queue
boost::condition cond; // a condition variable for communicating the queue state
bool empty()
{
return data.empty();
}
void thread1() // the consumer thread
{
while (true)
{
boost::mutex::scoped_lock lock(access);
cond.wait(lock, empty);
while (!empty())
{
int datum=data.top();
data.pop();
// do something with the data
}
}
}
void thread2() // the producer thread
{
while (true)
{
boost::mutex::scoped_lock lock(access);
data.push_back(1); // guaranteed random by a fair dice roll
cond.notify_one();
}
}
int main()
{
boost::thread t1(thread1);
boost::thread t2(thread2);
t1.join();
t2.join();
return 0;
}
I used a queue from the STL and threads, condition variables and mutexes from the Boost library. The stuff in boost is pretty much what is going to be in the standard C++ library in a few years so it is good to be familiar with it.
I only typed the code in, I have no way to test it. You'll probably find bugs. This is a good thing, threaded code is difficult and the best way to get good at it is lots of practice.