2

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.

andand
  • 17,134
  • 11
  • 53
  • 79
sufyan siddique
  • 1,461
  • 4
  • 13
  • 14

3 Answers3

4

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.

Andres Jaan Tack
  • 22,566
  • 11
  • 59
  • 78
0

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

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

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

cwh5635
  • 23
  • 6