场景:多线程应用程序使用的DLL中的全局变量 [英] Scenario: Global variables in DLL which is used by Multi-threaded Application
问题描述
假设我创建了一个DLL,导出一些用C ++编写的功能,用于单线程客户端。这个DLL声明了大量的全局变量,其中一些可能是const变量(只读),而另一些是可以修改的。无论如何,后来的事情都发生了变化,现在我希望相同的DLL能够与多线程应用程序一起工作(不需要修改DLL)。这意味着,几个线程从DLL访问函数和全局变量,并修改它们......等等。所有这些都可能导致全局变量持有不一致的值。
所以问题是,
我们可以做些什么在客户端代码中防止DLL的多重访问,并且同时确保每个线程运行在它自己的上下文中<(即,当它访问DLL时,DLL的全局值与以前相同)?
我们可以在客户端代码中做些什么来防止多重访问DLL,同时确保每个线程都运行在它自己的上下文中(也就是说,当它访问DLL时,DLL的全局值与以前相同)?
这是最难的部分。我认为顶层做这件事的唯一方法就是围绕现有的DLL创建一个包装。当它被调用时,它会恢复当前线程的状态(全局变量),并在对DLL的调用返回时保存它们。您需要知道DLL中的所有状态变量,并且能够读取/写入它们。
如果性能不是问题,则为整个DLL就足够了,并且是最容易正确实现的。这将确保只有一个线程一次访问(读取或写入)DLL。
Few months back, I had come across this interesting scenario asked by a guy (on orkut). Though, I've come up with a "non-portable" solution to this problem (have tested it with small code), but still would like to know what you guys have to say and suggest.
Suppose, I created a DLL, exporting some functionalities, written in C++, for single threaded client. This DLL declares lots of global variables, some maybe const variables (read-only) and others are modifiable.
Anyway, later things changed and now I want the same DLL to work with multi-threaded application (without modifying the DLL); that means, several threads access the functions and global variables from the DLL, and modify them.. and so on. All these may cause global variables to hold inconsistent values.
So the question is,
Can we do something in the client code to prevent multi-access of the DLL, and at the same time, ensuring that each thread runs in it's own context (meaning, when it gets access to the DLL, the DLL's global values are same as it was before)?
Can we do something in the client code to prevent multi-access of the DLL, and at the same time, ensuring that each thread runs in it's own context (meaning, when it gets access to the DLL, the DLL's global values are same as it was before)?
This is the hard part. I think the only way top do this would be to create a wrapper around teh existing DLL. When it is called, it would restore the state (global variables) for the current thread, and save them when the call to the DLL returns. You would need to know all of the state variables in the DLL, and be able to read/write them.
If performance is not an issue, a single lock for the entire DLL would suffice, and be the easiest to implement correctly. That would ensure that only one thread was accessing (reading or writing) the DLL at one time.
这篇关于场景:多线程应用程序使用的DLL中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!