The following code works fine for inserting and removing an element from a deque using two threads.
I would appreciate any help on how to make it better, especially in terms of thread safety.
#include "stdafx.h"
#include <deque>
#include <condition_variable>
#include <iostream>
#include <thread>
#include <mutex>
#define SLEEP_TIME 1
std::deque <int> q;
std::mutex _mu;
std::condition_variable cond;
void function1()
{
int count = 10;
while (count > 0)
{
std::unique_lock <std::mutex> locker(_mu);
q.push_front(count);
locker.unlock();
cond.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(SLEEP_TIME));
count--;
}
return;
}
void function2()
{
int data = 0;
while (data != 1)
{
std::unique_lock<std::mutex> locker(_mu);
cond.wait(locker);
data = q.back();
q.pop_back();
locker.unlock(),
std::cout << "T2 gets " << data << " from T1" << std::endl;
}
return;
}
int main() {
std::thread t2(function1);
std::thread t1(function2);
t1.join();
t2.join();
std::cout << "Thread Function Executed Successfully" << std::endl;
}