关于主线程与子线程式同步的问题

benjiamen 2008-06-07 09:23:21
主线程中开启了一个子线程,这个子线程是是在循环的展示各种效果的图片.当然在子线程的Execute方法中在不停的检测Terminated的值,从而退出Execute;
在主线程中有相按钮方法,方法有调用停止线程的方法TThread.Terminate; 现在问题是主线程如何等待或同步步为营个子线程的结束?
如 线程名为 thread1
thread.Terminate;
WiatForSingleObject(thread.Handle,3000);

这样行吗? 一般的作法是怎样的.
...全文
176 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
DumDum 2008-06-11
  • 打赏
  • 举报
回复
procedure thread.Execute;
begin
...
...
...
PostMessage(Handle,Message,wm_ThreadEnd,0,0);
end;

wm_ThreadEnd为自定义的消息,
窗口再定义一个消息处理函数
procedure WMThreadEnd(var message:TMessage);message wm_ThreadEnd;

进行下一步处理~~!
DumDum 2008-06-11
  • 打赏
  • 举报
回复
主线程一般是窗口之类的,你可以在子线程结束后发一个消息给窗口,窗口再根据消息进行下一步处理
liangpei2008 2008-06-11
  • 打赏
  • 举报
回复
学习~
DumDum 2008-06-11
  • 打赏
  • 举报
回复
但是使用waitfor后其他的线程就不能同时运行了~~!就没有使用线程的意义了
大大怪老张 2008-06-11
  • 打赏
  • 举报
回复
waitfor 在 TThread 中就是用 事件 来监控线程执行是否结束的。
僵哥 2008-06-11
  • 打赏
  • 举报
回复
var
I_Wait_Time_Out: Integer;

...
I_Wait_Time_Out := 3000;
while (I_Wait_Time_Out > 0) and (WiatForSingleObject(thread.Handle,1) = WAIT_TIMEOUT) do begin
Dec(I_Wait_Time_Out);
Application.ProcessMessage;
end;
僵哥 2008-06-11
  • 打赏
  • 举报
回复
WaitForSingleObject跟线程里面的WaitFor有差别吗?

var
I_Wait_Time_Out: Integer;

...
I_Wait_Time_Out := 3000;
while WiatForSingleObject(thread.Handle,1) = WAIT_TIMEOUT do begin
Dec(I_Wait_Time_Out);
Application.ProcessMessage;
end;
ZyxIp 2008-06-11
  • 打赏
  • 举报
回复
还有另一种方法是,每个子线程结束时给主线程发一个消息.

主线程收到消息后在进行下一步处理.
chl_seu 2008-06-11
  • 打赏
  • 举报
回复
1 waitfor
2 子线程计数,主线程check,用sleep(0)切换执行
大大怪老张 2008-06-07
  • 打赏
  • 举报
回复
procedure TForm1.Button9Click(Sender: TObject);
var
DemoThread : TDemoThread;
begin
DemoThread := TDemoThread.Create(true);

// do something...

DemoThread.Terminate;
DemoThread.WaitFor; // 等待 Execute 执行结束
FreeAndNil(DemoThread);
end;



下面是 function TThread.WaitFor: LongWord; 的在线帮助:

Waits for the thread to terminate and then returns the value of the ReturnValue property.

Delphi syntax:

function WaitFor: LongWord;


C++ syntax:

int __fastcall WaitFor(void);


Description

Call WaitFor to obtain the value of ReturnValue when the thread finishes executing. WaitFor doesn't return until the thread terminates, so the thread must exit either by finishing the Execute method or by exiting when the Terminated property is true.

1,183

社区成员

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

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