How can class method access be safely controlled in a C++ mutli threaded program using boost?

I want to translate some Java code into C++. One of the Java classes extends the Thread class and contains the following method:

 public static synchronized String createUniqueID() {
    //some code here
}

How can I synchronize (in the Java sense of the word) class methods in C++ using Boost? I have read about using boost::mutex for synchronizing access to shared data, but I am not sure how to apply this to C++ class methods.

Answers


The following is equivalent to a Java synchronized method in C++. In fact, it is exactly equivalent, with the obvious exceptions that it is written in a different language and a different threading library.

class Thing {
  public:
    static std::string createUniqueId () {
        boost::unique_lock<boost::mutex> synchronized(mutex_);
        // ... generate a unique id here.
    }

  protected:
    static boost::mutex mutex_;
};

Note that the mutex is protected, not private, allowing you to use the same mutex (as you should) in subclasses.


Use a static (i.e. class) mutex.


actually i do not understand what you said that "but I am not sure how to apply this to C++ class methods"

boost::mutex

you want to use, you must declare that. is not take effect now you must use

`boost::mutex::scoped_lock `

to effect it it can unlock automaticlly


Need Your Help

How do I connect to Postgresql server from Python?

python postgresql python-2.7 postgresql-9.1 raspberry-pi

My final goal is to setup a server on my raspberry pi which can connect to a local postgresql server.

iCloud & NSFileWrapper: Showing as 2 different files in Settings

ios icloud nsfilewrapper

I have an app that uses a UIDocument that is NSFileWrapper based. My file wrapper is a directory named "XXX.cp", with two sub-files "photo.data" and "photo.metadata". It seems to save and load