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:
  1. Processing events on editor module side
  2. Receive data and send result of events back to UI. 
Code of two main function execute on them can found bellow:



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);

Comments

  1. Hi Greg,

    I 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 ?

    ReplyDelete
    Replies
    1. 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

Post a Comment

Popular posts from this blog

Query commands execution

Hierarchy - UI improvement

Singleton pattern