Basically i create a thread and detach it, after some time i would like to exit it, i made a global variable that informs thread that it needs to be finished, however it never quits i believe it has something to do with sharing one var with two different threads (not attached to each other), one day i read about std::atomic that it somehow manages reads/writes but im not even aware how to declare/use it.
And heres the code
void CreateDWMTCPServer(int prt)
{
if (server != 0)
{
server_thread_finished = true;
while ( (!server_thread_free) && (server_thread_created)) {} // holds here forever
delete server;
server = 0;
server_thread_created = false;
}
PUSH_EVENT(event_display, "creating server...");
server = new TTCPWindowLayerServer();
server->CreateServer(prt);
server_thread_created = true;
std::thread ServerThread(std::bind(&TDWM::ProcessServerFrame, this));
ServerThread.detach();
}
Code above isnexecuted from main thread
Now thread code
void ProcessServerFrame()
{
if (server == 0) return;
server_thread_free = false;
while ( !server_thread_finished )
{
if (server_thread_lock_buffer_active) continue;
server->ProcessFrame(); //add any pending data to pdata buffer stream, accept or disconnect clients and thats all
TCPWindowLayerClient * p = server->clients;
while (p != 0)
{
if (p->LAST_EVENT == TCP_DATA_RECEIVED)
{
AddCommandsToDWMEvent(p);
ProcessPendingPackets(&events, Forms);
p->ppos = 0;
p->LAST_EVENT = TCP_NO_ACTION;
}
p = p->next;
}
}
server->Close();
server_thread_free = true;
KillServer();
}
As you can see theres a bool server_thread_finished (not to mention bad naming) that informs loop in a thread to stop executing this is main shared variable
After while loop thread changes another global variable server_thread_free so that while loop in main thread knows when to break, however it seems they are not switched cause std::thread uses var when main thread wants to update it, so how would i fix this sharing memory problem?
Notice
while ( (!server_thread_free) && (server_thread_created)) {}
In first chunk of code