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 this be thread safe (for each instance, not all instances together)?
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?
If answer to 1 and 2 are no, how can I make each instance thread safe?
The storage location has nothing to do with anything.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With