0

std::mutex crash on initial lock (Interesting thread releated bug with fix included!)

Have been writing some code to test out creating worker threads in C++ and came across an interesting bug where my program would crash on the first lock of the mutex. Thought it was an interesting little problem to solve. Hint: Crash isn’t necessarily 100%…

(Answer at bottom of post)

#include <stdio.h>
#include <thread>
#include <vector>
#include <mutex>
#include <atomic>
class WorkerThread
{
public:
  WorkerThread(const char* szName) 
    : m_threadName(szName)
    , m_thread(&WorkerThread::WorkerLoop, this)  { }
  ~WorkerThread()
  {
    m_bFinished = true;
    m_thread.join();
  }

private:

  void WorkerLoop()
  {
    m_mutex.lock();
    printf("run once");
    m_mutex.unlock();
  }

  std::thread			m_thread;
  std::atomic_bool	m_bFinished = false;
  std::string			m_threadName;
  std::mutex			m_mutex;
};


int main()
{
  WorkerThread workThread("first worker thread");
  
  return 0;
}
Click Here To View Answer:
Basically what’s happening is that because I was creating the thread during the class constructor, it would start running that thread while the class was still being constructed. So it is possible and extremely likely that when the newly spawned thread attempts to lock the mutex for the first time, the mutex hasn’t even been initalised during the class constructor yet!¬†An interesting little thread related bug and a dangerous one too! Could easily go unnoticed if by luck it didn’t crash on your machine.