How to use threads and queues in VC ++

I want to use two queues where the first queue will push the data into the queue and the second thread will delete the data from the queue. Can someone help me plz implement this in VC ++?

I am new to threads and queues.

+3
source share
2 answers

This is a producer / consumer problem, here is one implementation of this in C ++

+2
source

Here are some 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;
}

queue STL threads, Boost. boost - , ++ .

, . , . , , - .

+1

Source: https://habr.com/ru/post/1704483/


All Articles