我现在在一个多线程的程序~有个问题,请大家帮帮我!(在线待)

luinayi 2003-08-21 10:52:31
就是说每个线程都要同时读取一个值如计数器Count的值,怎么样才能不会冲突.
也就是有没有可以锁定这一段小程序的代码!
小程序如下:
读取 L_Count:=Count;
自增 Count:=Count+1;
每个线程都不能同时执行这段程序的办法.只能是等某一线程执行完才执行.
先谢谢大家了..
...全文
22 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
luinayi 2003-08-21
  • 打赏
  • 举报
回复
请问一下 是不是 Synchronize 就有提供互斥的功能!
luinayi 2003-08-21
  • 打赏
  • 举报
回复
我试试
我不懂电脑 2003-08-21
  • 打赏
  • 举报
回复
使用互斥呀
firstshine 2003-08-21
  • 打赏
  • 举报
回复
unit Unit2;

interface

uses
Classes;

Var
Count:Integer;

type
TestThread = class(TThread)
private
FTemp:Integer;

Procedure GetVar;
Procedure ReadFunc;
protected
procedure Execute; override;
end;

implementation

{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,

Synchronize(UpdateCaption);

and UpdateCaption could look like,

procedure TestThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }

{ TestThread }

procedure TestThread.Execute;
begin
ReadFunc;
end;

procedure TestThread.GetVar;
begin
FTemp:=Count;
Inc(Count);
end;

procedure TestThread.ReadFunc;
//这是一个读取全局变量的例子
var
L_Count:Integer;
begin
Synchronize(GetVar);//这一句最关键
L_Count:=FTemp;
//下面,用L_Count来干什么都可以了
end;

end.
ld9702 2003-08-21
  • 打赏
  • 举报
回复
这样是否和单线程一样了呢?
lxpbuaa 2003-08-21
  • 打赏
  • 举报
回复
TThread1.Oper;
begin
L_Count:=Count;
end;

TThread1.Execute;
begin
Synchronize(Oper);
end;

TThread2.Oper;
begin
Count:=Count+1;
end;

TThread2.Execute;
begin
Synchronize(Oper);
end;

—————————————————————————————————
宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
—————————————————————————————————



5,386

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧