C++ riddle
This time small C++ riddle which took me some time to figure out :)
Background:
My editor currently use sockets connection to pass data between Qt UI and "Editor module" in engine. Inside editor module this happen on two threads:
Issue:
This worked fine except my editor were crashing sometimes. This happen on random operations : moving, selecting, changing properties. Visual Studio debugger where showing me that crash were happening in this code:
Data in eventResult was looking like corrupted event or already deleted class.
Question:
What is wrong with this code :D ?
while (!wrAtomic::compareexchange(&m_eventsToFinalize, eventResult, eventResult->next) == eventResult->next);
should be:
while (wrAtomic::compareexchange(&m_eventsToFinalize, eventResult, eventResult->next) == eventResult->next);
Background:
My editor currently use sockets connection to pass data between Qt UI and "Editor module" in engine. Inside editor module this happen on two threads:
- Processing events on editor module side
- Receive data and send result of events back to UI.
Issue:
This worked fine except my editor were crashing sometimes. This happen on random operations : moving, selecting, changing properties. Visual Studio debugger where showing me that crash were happening in this code:
do { eventResult->next = m_eventsToFinalize; } while (wrAtomic::compareexchange(&m_eventsToFinalize, eventResult, eventResult->next) == eventResult->next);
Data in eventResult was looking like corrupted event or already deleted class.
Question:
What is wrong with this code :D ?
Greg
EDIT: There was small mistake in original version of code which should not be there (I fixed this in post). Line :while (!wrAtomic::compareexchange(&m_eventsToFinalize, eventResult, eventResult->next) == eventResult->next);
should be:
while (wrAtomic::compareexchange(&m_eventsToFinalize, eventResult, eventResult->next) == eventResult->next);
Hi Greg,
ReplyDeleteI didn't do C++ for years and just tried to decipher your code for fun so I might say some bullshit.
Anyway what happens if m_eventsToFinalize == nullPtr and you try compareExchange on &m_eventsToFinalize ?
There was small mistake in code when I was recovering old version (I added EDIT section with noted change). Good thing this don't affect this question :) CompareExchange use pointer on m_eventsToFinalize (&m_eventsToFinalize) to replace content of variable m_eventsToFinalize. If it's nullptr then it will just replace it with new value without any problems.
Delete