Question

I'd like to make a system, that loads options out of an XML-file into a ptree and acess this ptree across multiple threads. Sofar, i have mad a simple class, that is accessible to every thread, that contains the methods put(id) and get(). Unfortunately, ptree doesn't appear to be threadsafe, so the program crashes a lot. Is there a way, to make ptree threadsafe? Or is there a better solution all together?

Était-ce utile?

La solution

You can use the guardian template structure described int this blog post.

Basically, you will create a guardian<ptree> instead of a plain ptree. A guardian is a opaque structure that holds a mutex alongside its data. The only way to access the data is via a guardian_lock, that will lock the mutex.

guardian<ptree> xml;

//thread 1
{
  guardian_lock<ptree> lock(xml);
  lock->put("a", "b");
}

//thread 2
{
  guardian_lock<ptree> lock(xml);
  lock->put("c", "d");
}

As you can only access the inner ptree through the lock, and the lock locks the mutex, you will never have race conditions.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top