50

synchronized in Java can guarantee thread-safety when accessing a shared object. What about C++?

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
Don Lun
  • 2,717
  • 6
  • 29
  • 35

4 Answers4

52

Use the following in C++:

#include <mutex>

std::mutex _mutex;

void f()
{
     std::unique_lock<std::mutex> lock(_mutex);
     // access your resource here.
}
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
10

Despite this question has been already answered, by the idea of this article I made my version of synchronized keyword using just standard library (C++11) objects:

#include <mutex>
#define synchronized(m) \
    for(std::unique_lock<std::recursive_mutex> lk(m); lk; lk.unlock())

You can test it like:

#include <iostream>
#include <iomanip>
#include <mutex>
#include <thread>
#include <vector>

#define synchronized(m) \
    for(std::unique_lock<std::recursive_mutex> lk(m); lk; lk.unlock())

class Test {
    std::recursive_mutex m_mutex;
public:
    void sayHello(int n) {
        synchronized(m_mutex) {
            std::cout << "Hello! My number is: ";
            std::cout << std::setw(2) << n << std::endl;
        }
    }    
};

int main() {
    Test test;
    std::vector<std::thread> threads;
    std::cout << "Test started..." << std::endl;

    for(int i = 0; i < 10; ++i)
        threads.push_back(std::thread([i, &test]() {
            for(int j = 0; j < 10; ++j) {
                test.sayHello((i * 10) + j);
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
            }
        }));    
    for(auto& t : threads) t.join(); 

    std::cout << "Test finished!" << std::endl;
    return 0;
}

This is just an approximation of synchonized keyword of Java but it works. Without it the sayHello method of the previous example can be implemented as the accepted answer says:

void sayHello(unsigned int n) {
    std::unique_lock<std::recursive_mutex> lk(m_mutex);

    std::cout << "Hello! My number is: ";
    std::cout << std::setw(2) << n << std::endl;
}
Winter
  • 3,894
  • 7
  • 24
  • 56
Akira
  • 4,385
  • 3
  • 24
  • 46
  • This would be great if implemented as as a template, but I've found, with a few well known exception (e.g. _assert_), code implemented with _#define_s is difficult to debug. – gerardw Dec 12 '18 at 21:06
6

There is no keyword in C++03 equivalent to synchronized in Java . But you can use Mutex to guarantee safety of thread.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

C++ does not have built-in threading or synchronization (yet), you have to use libraries for that. Boost.Thread is a good portable library that is designed to be compatible with the proposed threading facilities in C++0x.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283