从dll导入的类的线程安全
我有一个 dll,它导出接口,
class Qwe{
virtual void a() = 0;
virtual void b() = 0;
};
extern "C" Qwe* createQwe();
我将其加载到程序中并创建多个 Qwe 对象。问题是从不同线程访问这些对象是否安全?我应该为每个对象打开新的库实例,还是一个就足够了?
不使用静态数据成员,并且库函数本身不是线程安全的。
为了更好地定义问题...导出的类可能看起来像
class QweImpl : public Qwe{
public:
virtual void a() {
std::fill(data.begin(), data.end(), 1.0)};
private:
std::vector<double> data; };
QweImpl::a() 这里安全吗?从某种意义上说,两个不同的 QweImpl 对象可以同时调用它们的 a() 函数?
I have a dll which exports the interface
class Qwe{
virtual void a() = 0;
virtual void b() = 0;
};
extern "C" Qwe* createQwe();
I load it in my program and create multiple Qwe objects. The question is whether accessing those objects from different threads is safe? Shall I open the new library instance for each object, or one is enough?
No static data members are used, and library functions are not thread-safe by themselves.
To define the question better... exported class may look like this
class QweImpl : public Qwe{
public:
virtual void a() {
std::fill(data.begin(), data.end(), 1.0)};
private:
std::vector<double> data; };
is QweImpl::a() safe here? In the sense that two different QweImpl objects can simultaneously call their a() functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Windows 中,您只能加载库一次。进一步尝试加载库只会增加引用计数器。因此,“为每个对象加载一个库”是行不通的。
如果您的 Qwe 类包含数据成员或字段(我无法判断是否包含),那么您可以使用 Qwe 内部的关键部分(或其他一些机制)来保护对共享内存的访问。
In windows you can only load a library once. Further attempts to load a library only increments a reference counter. So therefore 'loading a library for each object' is a non-starter.
If your Qwe class contains data members or fields, which I can't tell if it does or not, than you could protect access to shared memory using critical sections (or some other mechanism) inside of Qwe.
如果类具有可以跨多个线程访问的成员,那么您将必须使用同步机制来控制访问。
If the class has members that can be accessed across multiple threads then you will have to use a synchronization mechanism to control access.