FloatToStr/DateToStr的线程安全性 [英] Thread-Safeness of FloatToStr / DateToStr

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

问题描述

我刚刚在文档中发现FloatToStrDateToStr在其单参数重载中不是线程安全的.原因是它们访问存储在全局变量中的本地化信息.

I just found in the documentation that FloatToStr and DateToStr are not thread-safe in their one-paramater overloads. The reason is that they access localization information stored in global variables.

我的问题是:如果我在运行时不更改格式设置,这是否有实际意义?据我了解,只要每个人都只能读取格式设置(即使是从多个线程读取),我也很安全.

My question is: is this of any practical relevance if I do not change the format settings at runtime? As far as I understand it, I'm on the safe side as long as everyone only reads the format settings - even from multiple threads.

是真的还是我在这里错过了什么?

Is that true or am I missing something here?

谢谢.

推荐答案

FloatToStr,DateToStr和其他类似的函数正在读取全局格式设置.因此,如果您的应用程序不更改这些函数调用的这些设置,那么它是线程安全的.相反的以下代码不是线程安全的:

FloatToStr, DateToStr and others similar functions are reading global format settings. So, if your application does not change these settings for these function calls, then it is thread safe. The following code on opposite is not thread safe:

DecimalSeparator := ',';
try
  s := FloatToStr(123.45);
finally
  DecimalSeparator := '.';
end;

当需要胎面安全性和本地"格式设置时,则必须使用重载函数,这些函数作为最后一个参数:AFormatSettings:TFormatSettings.因此,为了使上述代码线程安全,您必须编写:

When you need the tread safety and "local" format settings, then you have to use overloaded functions, which take as last parameter: AFormatSettings: TFormatSettings. So, to make above code thread safe you have to write:

var
  fs: TFormatSettings;

GetLocaleFormatSettings(GetThreadLocale, fs);
fs.DecimalSeparator := ',';
s := FloatToStr(123.45, fs);

注意:

  1. GetLocaleFormatSettings和fs初始化可以被调用一次,然后fs可以被多次使用.这样可以加快代码的速度.
  2. 可以使用TFormatSettings.Create代替GetLocaleFormatSettings.我不确定是什么时候引入的,但是我在Delphi XE中看到了.

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

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