场景:多线程应用程序使用的DLL中的全局变量 [英] Scenario: Global variables in DLL which is used by Multi-threaded Application

查看:621
本文介绍了场景:多线程应用程序使用的DLL中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月前,我遇到了一个人(orkut)提出的有趣场景。尽管如此,我已经想出了一个针对这个问题的非便携式解决方案(已经用小代码对其进行了测试),但仍想知道你们应该说些什么和建议。



假设我创建了一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆