>> So my question is - where should I put my mainLoop() function in my custom thread?
It looks like you're attempting to implement a "user interface thread", but you may only need a "worker thread". Read more about it here: http://msdn.microsoft.com/en-us/library/975t8ks0.aspx

>> But it's not working - some heap errors appears.
One error I see is in receiveMessage() - once getMessageCount() returns, the count is meaningless. You need to get the count and call RemoveTail() while inside the critical section.

gg