开发者

mutex as class member

开发者 https://www.devze.com 2023-03-04 15:39 出处:网络
class temp { boost::mutex mx; void CriticalCo开发者_JAVA百科de() { boost::mutex::scoped_lock scoped_lock(mx);
 class temp
 {
    boost::mutex mx;
    void CriticalCo开发者_JAVA百科de() {
        boost::mutex::scoped_lock scoped_lock(mx); 
        //Do Something
        return;
    }
 }
  1. If this class is allocated on the heap (temp* T = new temp()), will this be thread safe (for each instance, not all instances together)?

  2. If I make boost::mutex mx -> boost::mutex* mx, and allocate it in the constructor so it will be allocated on the heap, will the code be thread safe also?

  3. If answer to 1 and 2 are no, how can I make each instance thread safe?


1)if this class is allocated on the heap (temp* T = new temp()) , will this be thread safe (for each instance, 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 make boost::mutex mx -> boost::mutex* mx , and allocate it in the constructor so it will be allocated on the heap , will the code be thread safe also ?

Yes. But thread safe only on a per-instance basis.

3)if answer to 1 and 2 are now , how can i make each instance thread safe ?

The answers are yes so you are fine.

In case, someone else wonders how to make all instances thread safe with one lock -- you can make mx a static variable of the class.


The storage location has nothing to do with anything.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消