Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What feature corresponds to 'synchronized' in Java?

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

like image 587
Don Lun Avatar asked Mar 25 '11 07:03

Don Lun


People also ask

What is synchronized function in Java?

Java Synchronized Method Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

Which of these is synchronized in Java?

Explanation: Vector out of the list is synchronized.

What is synchronized variable in Java?

Synchronized keyword in Java is used to provide mutually exclusive access to a shared resource with multiple threads in Java. Synchronization in Java guarantees that no two threads can execute a synchronized method which requires the same lock simultaneously or concurrently.


Video Answer


2 Answers

Use the following in C++:

#include <mutex>  std::mutex _mutex;  void f() {      std::unique_lock<std::mutex> lock(_mutex);      // access your resource here. } 
like image 200
Yakov Galka Avatar answered Sep 21 '22 16:09

Yakov Galka


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; } 
like image 41
Akira Avatar answered Sep 23 '22 16:09

Akira