class temp
{
boost::mutex mx;
void CriticalCo开发者_JAVA百科de() {
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?
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.
精彩评论