3

In C#/Java I can easily make any thread-unsafe code to be thread-safe. I just introduce special "lockObj" and use it like that:

    private object lockObj = new object();

    void ThreadSafeMethod()
    {
        lock (lockObj)
        {
            // work with thread-unsafe code
        }
    }

(some people just using lock (this) but this is not recomended)

What is easiest and fastest C++ equivalent? I can use C++11.

Community
  • 1
  • 1
Oleg Vazhnev
  • 22,231
  • 49
  • 161
  • 290

3 Answers3

3

If you can use C++11, use a std::mutex (if you can not use C++11, use boost::mutex)

private:
    std::mutex m;

    void ThreadSafeMethod()
    {
        std::lock_guard<std::mutex> lock(m);
        // work with thread-unsafe code
    }
Torsten Robitzki
  • 2,979
  • 1
  • 20
  • 34
0

A Mutex is probably the closest native C++ equivalent. For the closest equivalent that includes the use of external libraries, you need a Monitor.

However, std::lock is probably the straightest line (the provided code example uses std::mutex).

Robert Harvey
  • 173,679
  • 45
  • 326
  • 490
0

You can use std::lock if you have a C++ compiler or the standard primitives provided by your OS, eg.: WaitForSingleObject on Windows or pthread_mutex_lock on Unix/Linux.

ahoka
  • 304
  • 2
  • 4