Delphi DLL - 线程安全 [英] Delphi DLL - thread safe

查看:280
本文介绍了Delphi DLL - 线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Delphi DLL,我想把它加载到我的应用程序里面一个线程(多于一个,完全是)。该DLL只是创建一个对象,然后它使用它并销毁它。对于这个观点,DLL代码是线程安全的。



但是,如果我在线程中加载该DLL,会发生什么? DLL是否仍然线程安全?我应该知道什么线程加载DLL?我看到VCL有IsMultThread属性,当我们创建一个线程时设置,但是dll会收到通知,还是应该手动执行?

解决方案

最常见的缺陷是使用全局变量。只要您不使用任何全局变量(或正确地同步访问您使用的变量),您将是一个很长的路线安全。



IsMultiThread 用于例如内存管理器在单线程情况下进行优化。就我个人而言,我觉得这几天是不值得的优化,因为几乎所有有用的代码都有一些描述的线程。我刚刚在你的DLL开始时将 IsMultiThread 设置为True。在您的DLL .dpr文件的开始 / end 块中,或在您单位的初始化部分中,相当于相同的事情。



要直接回答您的问题,您的DLL中的 IsMultiThread 的实例将不会设置为true除非你在该DLL中创建一个线程。由于您在EXE中创建线程,所以您需要在DLL中自行执行。



更一般来说,在不知道代码的情况下,不太可能对线程安全性进行说明它的作用和你实际上是什么意思的线程安全。后一点可能听起来很奇怪,但是我指的是Eric Lippert着名的着名<​​a href =http://blogs.msdn.com/b/ericlippert/archive/2009/10/19/what -is-this-thing-you-call-thread-safe.aspxrel =noreferrer>这是什么你所说的线程安全?文章。


I have a Delphi DLL and I want to load it in my app inside a thread (more than one, to be exactly). The DLL just creates a object, then it uses it and destroys it. For that point of view, the DLL code is thread safe.

But what happens if I load that DLL in a thread? Is the DLL still going to be thread safe? What should I know about threads loading DLL? I have seen that the VCL has the IsMultThread property that is set when we create a thread, but will the dll get notified about that or should I do it manually?

解决方案

The most common pitfall is use of global variables. So long as you don't use any global variables (or properly synchronise access to the ones you do use) you will be a long way towards thread safety.

IsMultiThread is used by, for example, the memory manager to make optimisations in the single threaded case. Personally I don't feel this is a worthwhile optimisation these days since practically all useful code has threads of some description. I'd just set IsMultiThread to True at the start of your DLL, e.g. in the begin/end block of your DLL .dpr file, or in one of your unit's initialization sections which amounts to the same thing.

To answer your question directly, the instance of IsMultiThread in your DLL will not be set true unless you create a thread in that DLL. Since you create the threads in your EXE you need to do it yourself in the DLL.

More generally, it's simply impossible to say much about thread safety of your code without knowing what it does and what you actually mean by thread safe. The latter point may sound odd, but what I'm referring to is the issue discussed in Eric Lippert's famous What is this thing you call "thread safe"? article.

这篇关于Delphi DLL - 线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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