delphi 线程全局变量copy
来源:互联网 发布:耐克网络代理 编辑:程序博客网 时间:2024/05/16 15:16
delphi多线程如果使用对于变量的访问会出现安全的问题。对于局部变量与对象内部变量,每个线程对象都会有拷贝,因此不会相互干扰,但是如果访问的是全局变量呢?
那么就会出现问题,全局变量的值就会无法确定。我们看一下列子
unit ThreadCopy;interfaceuses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;type TForm1 = class(TForm) btn1: TButton; edt1: TEdit; procedure btn1Click(Sender: TObject); private { Private declarations } public { Public declarations } end;var Form1: TForm1;implementation{$R *.dfm}threadvar GlobalStr : string;type TTLSThread=class(TThread) private FNewStr : string; protected procedure Execute;override; public constructor Create(const ANewStr : string); end;procedure SetGlobalStr(str : string);begin if str=' ' then messagebox(0,PChar(GlobalStr),'this str is..',MB_OK) else GlobalStr:=str;end;{ TTLSThread }constructor TTLSThread.Create(const ANewStr: string);begin FNewStr:=ANewStr; inherited Create(False);end;procedure TTLSThread.Execute;begin FreeOnTerminate:=True; SetGlobalStr(FNewStr); SetGlobalStr(' ');end;procedure TForm1.btn1Click(Sender: TObject);begin SetGlobalStr('hello'); SetGlobalStr(' '); TTLSThread.Create('DilBret'); Sleep(100); SetGlobalStr(' ');end;end.
全局变量
GlobalStr 使用的threadvar进行的定义,那么这样定义会有什么好处呢?如果定义为threadvar那么当线程访问GlobalStr 时,并不是使用GlobalStr,而是使用GlobalStr 的拷贝,因此并不会影响其他线程的访问。大家可以尝试运行上面的代码。
- delphi 线程全局变量copy
- copy() delphi
- delphi中copy函数
- delphi中copy函数
- ◆Delphi多线程编程之五不同类线程读写全局变量-阻塞和锁定◆
- delphi 线程
- delphi线程
- delphi 线程
- PKG全局变量线程安全问题
- 全局变量的线程安全性
- Delphi中Copy的使用
- delphi copy 字符串部分复制
- DELPHI copy,pos函数用法
- 线程!线程!!线程!!!(Delphi版)
- 线程!线程!!线程!!!(Delphi版)
- 线程!线程!!线程!!!(Delphi版)
- pthread 子线程全局变量访问
- delphi 全局变量的定义与初始化赋值
- 浅尝ssh框架开篇
- 遗传算法(转自:http://bbs.csdn.net/topics/360128430)
- java 字符串解析(转自:http://bbs.csdn.net/topics/360128430)
- 为什么我们要用Spring?
- Android之使用AchartEngineActivity引擎绘制柱状图、曲线图
- delphi 线程全局变量copy
- tomcat集群
- 使用 od 显示二进制文件
- TCP/IP
- freemarker入门例子
- oracle存储过程错误跟踪(保存错误行号,错误代码,错误信息)
- .net 下载文件的方法 总结
- Struts的Acion中如何取得Spring管理的bean
- 使用Nginx反向代理来实现简单的负载均衡