Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mutex as class member

 class temp
 {
    boost::mutex mx;
    void CriticalCode() {
        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?

like image 541
shd Avatar asked May 10 '11 08:05

shd


2 Answers

The storage location has nothing to do with anything.

like image 138
Lightness Races in Orbit Avatar answered Oct 18 '22 18:10

Lightness Races in Orbit


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.

like image 41
Aater Suleman Avatar answered Oct 18 '22 18:10

Aater Suleman