I'm trying to create a simple consumer/producer code for learning, in which a producer pushes numbers into a stack, and consumer threads print the numbers, heres what I got:
const int N_THREADS = 10;
const int N_TESTS = 100;
bool finished = false;
queue<int> q;
void produce()
{
for (int i = 0; i < N_TESTS; i++)
{
q.push(i);
cv.notify_all();
}
finished = true;
}
void consume()
{
while (!q.empty() || !finished)
{
unique_lock<mutex> lock(m);
cv.wait(lock, [] {return !q.empty(); });
int i = q.front();
cout << i << endl;
q.pop();
}
}
int main()
{
//thread that will be used for producing
thread producer(produce);
//vector of consumer threadss
vector<thread> consumers(N_THREADS);
for (int i = 0; i < N_THREADS; i++)
{
consumers[i] = thread(consume);
}
//joining all threads
producer.join();
for (int i = 0; i < N_THREADS; i++)
{
consumers[i].join();
}
return 0;
}
However, when i run the code it prints the numbers but it just freezes, it never ends:
What can be done for it to end?