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.


Need Your Help

Count all records from midnight until now()

sql ruby postgresql time pg

I'm trying to grab all records created from midnight of the current day until the time a button is pressed.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.