Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ analog of C#/Java lock(object)

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.

like image 432
Oleg Vazhnev Avatar asked Apr 17 '26 21:04

Oleg Vazhnev


1 Answers

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
    }
like image 55
Torsten Robitzki Avatar answered Apr 19 '26 12:04

Torsten Robitzki