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: