views:

534

answers:

2

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.

+2  A: 

This is the producer / consumer problem, here is one implementation of it in c++

tarn
+1  A: 

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.

1800 INFORMATION
Hi,my requirement is there is a function which creates one thread and passes the data for further processing which looks like void MyFunc(char *data) { CreateThread(NULL,0,build_data,(void *)data,0,NULL); } Now i want to modify the above code
I want to introduce a queue class and want to create two threads so that 1st thread can invoke a function which writes the data to the queue and the 2nd thread reads the data from the queue. Please introduce mutex if required. Can you tell me how to implement the above in VC++. Thanks
Not really sorry, you should probably create a new question that includes all of the code you currently have. I don't really understand the requirement
1800 INFORMATION