可变关键字和线程安全
我有一个抽象基类,
class Map {
public:
virtual Value get(Key const &) const;
};
一个来自外部库的数据库类
class Database {
public:
// logically const and thread-safe
Value get(Key const &key);
};
实现开始
class PersistentMap : public Map {
Database db;
public:
Value get(Key const &key) const
{ return const_cast<Database &>(db).get(key); }
};
,我从一个像 const_cast 的数量开始超出范围的 ,我通过添加一个 mutable< /code> 说明符到 PersistentMap::db
(以及一条提醒自己它丑陋的注释)。
- 我第一次尝试 const_cast 是线程安全的吗?
- 我的新方法是线程安全的,还是应该将
db
标记为易失性
?
I have an abstract base class
class Map {
public:
virtual Value get(Key const &) const;
};
a database class from an external library
class Database {
public:
// logically const and thread-safe
Value get(Key const &key);
};
and I started with an implementation like
class PersistentMap : public Map {
Database db;
public:
Value get(Key const &key) const
{ return const_cast<Database &>(db).get(key); }
};
As the number of const_cast
s grew beyond bounds, I got rid of them by adding a mutable
specifier to PersistentMap::db
(and a comment to remind myself of its ugliness).
- Was my first attempt with
const_cast
thread-safe? - Is my new approach thread-safe, or should
db
also be markedvolatile
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这完全取决于 Database::get 是否是线程安全的。如果它包含阻止并发访问的锁,或者对于并发访问是安全的,那么您的代码可以使用 const_cast 或 mutable。使用 volatile 是完全无关的。
It depends entirely on whether Database::get is thread-safe or not. If it contains locks to prevent concurrent access, or is otherwise safe for concurrent access, then your code is fine with either the const_cast or the mutable. Using volatile is completely irrelevant.