Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

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.

Upvotes: 3

Views: 433

Answers (3)

ahoka
ahoka

Reputation: 412

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.

Upvotes: 0

Torsten Robitzki
Torsten Robitzki

Reputation: 2555

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
    }

Upvotes: 3

Robert Harvey
Robert Harvey

Reputation: 180788

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).

Upvotes: 0

Related Questions