线程同步

xiaocongzhi 2009-02-14 11:47:03
我用两个线程给全局数组赋值,并把两个线程赋值的结果分别显示在ListBox1与ListBox2中,为什么用临界区同步与用互斥对象同步结果不一样。
临界区同步ListBox1中显示1--100,ListBox2中显示101--200.而用互斥对象同步ListBox1,ListBox2都显示1--100.
望指点!
...全文
218 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
dadahacker 2009-03-01
  • 打赏
  • 举报
回复
贴出代码,只有查看代码才知道,肯定是你的代码的问题,既然是同步,技术不一样,但是实现的目的肯定是一样的,仔细走读你的代码。
liangpei2008 2009-02-15
  • 打赏
  • 举报
回复
把代码贴出来!
不贴代码一切都是空谈!
simonhehe 2009-02-14
  • 打赏
  • 举报
回复
昨天有人问过


unit utMutex;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure SetItem(Sender: TObject);
public
{ Public declarations }
end;

TtestThread = class(TThread)
protected
procedure execute; override;
end;
var
Form1: TForm1;


implementation

{$R *.dfm}
const
MAX = 128;
var
//cs : TRTLCriticalSection;
DoFlag : integer = 0;
hMutex : THandle = 0;
NextNumber : integer = 0;
iArr : array[1..MAX] of integer;

function GetNextNumber: integer;
begin
result := NextNumber;
inc(NextNumber);
end;
{ TtestThread }

procedure TtestThread.execute;
var
i : integer;
begin
inherited;
FreeOnTerminate := True;
OnTerminate := Form1.SetItem;
//EnterCriticalSection(cs);
if WaitForSingleObject(hMutex, INFINITE) = WAIT_OBJECT_0 then
for i := 1 to MAX do
begin
iArr[i] := GetNextNumber;
sleep(5);
end;
//LeaveCriticalSection(cs);
ReleaseMutex(hMutex);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
//InitializeCriticalSection(cs);
hMutex := CreateMutex(nil,false,nil);
TtestThread.Create(false);
TtestThread.Create(false);
end;

procedure TForm1.SetItem(Sender: TObject);
var
i : integer;
begin
inc(DoFlag);
if DoFlag = 2 then
begin
for i := 1 to MAX do
memo1.Lines.Add(inttostr(iArr[i]));
//DeleteCriticalSection(cs);
CloseHandle(hMutex);
end;
end;

end.
yc_8301 2009-02-14
  • 打赏
  • 举报
回复
哦。有这样的问题。
友情up!
关注中...
xiaocongzhi 2009-02-14
  • 打赏
  • 举报
回复
1楼的:
我是问为什么会不一样?
我仔细查了好几遍 还是查不出问题。我又用“信号量对象”做了同步 与临界区同步是一样的。
zshsuming 2009-02-14
  • 打赏
  • 举报
回复
学习

1,183

社区成员

发帖
与我相关
我的任务
社区描述
Delphi Windows SDK/API
社区管理员
  • Windows SDK/API社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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