Mutex as a member of the class

class temp { boost::mutex mx; void CriticalCode() { boost::mutex::scoped_lock scoped_lock(mx); //Do Something return; } } 
  • If this class is allocated on the heap ( temp* T = new temp() ), will it be thread safe (for each instance, and not for all instances together)?

  • If I do boost::mutex mxboost::mutex* mx and allocate it in the constructor so that it is allocated on the heap, will the code be thread safe as well?

  • If the answer to 1 and 2 is not, how can I make the thread of each instance safe?

+8
c ++ multithreading boost mutex
source share
3 answers

1) if this class is allocated on the heap (temp * T = new temp ()), will it be thread safe (for each instance, are not all instances together?

Yes. Since mx is not a static member of the class, there will be one lock per instance of the class.

2) if I create boost :: mutex mx → boost :: mutex * mx and allocate it in the constructor so that it is allocated on the heap, will the code be thread safe as well?

Yes. But thread safety is supported only for each instance.

3), if now the answer is 1 and 2, how can I make the thread of each instance safe?

The answers are yes, so you're fine.

In case someone else asks how to make all instances threads safe with one lock - you can make mx a static class variable.

+7
source share

The storage location has nothing to do.

+2
source share

Yes, the CriticalCode() method will be a safe thread in both cases.

0
source share

All Articles