What i tried to do:
I tried to make program witch goal is add elements to the queue (in thread) and display data about queue (You can see data to display in main). Before that i wanted to delete one element form queue (every two seconds) and adding new element (every one second).
Code
#include <iostream>
#include <queue>
#include <thread>
#include <Windows.h>
using std::queue;
using std::cout;
void loadQueue(queue<int> &toLoad)
{
for(int i = 0; i < 100; i++)
{
toLoad.push(i);
Sleep(1000);
}
}
int main(void)
{
queue<int>toLoad;
std::thread(loadQueue, std::ref(toLoad));
while(true)
{
cout << "SIZE OF QUEUE : " << toLoad.size() << '\n' << '\n';
cout <<"FRONT :" << toLoad.front() << '\n' << '\n';
cout <<"BACK : " << toLoad.back() << '\n';
toLoad.pop();
Sleep(2000);
}
}
About error
When I start program i don't see enything. Program close right away. Visual Studio show me this messege:
std::thread(loadQueue, std::ref(toLoad));
— this declares a local temporary variable of typestd::thread
. Since it is unnamed, temporary object, it gets destructed immediately after its creation. But see the destructor ofstd::thread
— quote: "If*this
has an associated thread(joinable() == true)
,std::terminate()
is called. " You need to join the threads you create. (Or detach, but this is advanced usage.)Sleep(1000);
-->#include <chrono> ... std::this_thread::sleep_for(1000ms);
. In other words, use the standard thread functions, not Windows specific ones.deque
, that results as an Undefined Behavior. All accesses to 'toLoad` must be done in amutex
protected area.