互斥量作为类成员
class temp
{
boost::mutex mx;
void CriticalCode() {
boost::mutex::scoped_lock scoped_lock(mx);
//Do Something
return;
}
}
- 此类在堆上分配 (
temp* T = new temp()
),这是否是线程安全的(对于每个实例,而不是所有实例)? 如果我制作
boost::mutex mx
->boost::mutex* mx
,并在构造函数中分配它,以便它将在堆上分配,代码也是线程安全的吗?如果 1 和 2 的答案是否定的,如何使每个实例线程安全?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1) 如果此类分配在堆上 (temp* T = new temp()) ,这是否是线程安全的(对于每个实例,而不是所有实例在一起?
是的。因为 mx 不是一个类的静态成员,该类的每个实例将有一个锁
2) 如果我使 boost::mutex mx -> 。 boost::mutex* mx ,并在构造函数中分配它,这样它将在堆上分配,代码也是线程安全的吗?
是的。但线程安全仅在每个实例的基础上。
3)如果现在回答1和2,我怎样才能使每个实例线程安全?
答案是肯定的,所以你没问题。
万一,其他人想知道如何使用一个锁使所有实例都是线程安全的——您可以使 mx 成为类的静态变量。
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.
是的,
CriticalCode()
方法在这两种情况下都是线程安全的。Yes, the method
CriticalCode()
will be thread safe in both cases.