【zt】delphi线程同步问题(postmessage)
通过postmessage同步线程的方法。
原帖地址:http://blog.csdn.net/jfyes/archive/2007/01/18/1487057.aspx
呵呵,N久前的问题现在忘记了,搞得我找了一个小时的原因才找出是线程里面更
新VCL,出现了主线程阻塞的问题,刚开始还莫名其妙的不知所以然,后来发现自己的线程
内用了Synchronize函数,难怪把网线一拔,Socket接收进入阻塞线程状态,可是主线程也
同时被阻塞了。
VCL不支持线程更新,记得在FastPC中用的最多也是线程,处理VCL只
有用一种方法最能解决问题的是PostMessage将消息邮寄给主线程,得以解同步问题。呵呵,
长时间不用,就会忘记。如果用了PostMessage,那线程同步函数就没有必要在用了。
修改后得以正常运行。
1const
2 WM_THREAD_MSG = WM_USER + $FF;
3
4procedure WMThread_msg(var Msg: TMessage); message WM_THREAD_MSG;
5
6type
7 TDataPack = record
8 ID: WORD;
9 DataSize: Integer;
10 Data: PChar;
11 end;
12 PDataPack = TDataPack
13
14procedure TDataPack.Execute;
15var
16 AData: TDataPack;
17begin
18 inherited;
19 FBindIndex := socket_state;
20 while (not self.Terminated) and (FBindIndex > -1)do
21 begin
22 try
23 //Synchronize(SynchronizeMethod); //线程同步
24 FillChar(AData, SizeOf(AData), #0);
25 if ReadSocket(FSocket[FBindIndex], AData) then
26 PostMessage(Application.MainForm.Handle, WM_THREAD_MSG, 0, Longint(@PDataPack));
27
28 Sleep(FWaitTime);
29 except on E: Exception do
30 WriteLog(g_ProLogFile, E.Message);
31 end;
32 end;
33
34end;
35procedure TMainForm.WMThread_msg(var Msg: TMessage);
36var
37 Data: PDataPack;
38begin
39 Data := PDataPack(Msg.lParam);
40 if Data <> nil then
41 begin
42 //TODO: 处理数据
43 end;
44end;
2 WM_THREAD_MSG = WM_USER + $FF;
3
4procedure WMThread_msg(var Msg: TMessage); message WM_THREAD_MSG;
5
6type
7 TDataPack = record
8 ID: WORD;
9 DataSize: Integer;
10 Data: PChar;
11 end;
12 PDataPack = TDataPack
13
14procedure TDataPack.Execute;
15var
16 AData: TDataPack;
17begin
18 inherited;
19 FBindIndex := socket_state;
20 while (not self.Terminated) and (FBindIndex > -1)do
21 begin
22 try
23 //Synchronize(SynchronizeMethod); //线程同步
24 FillChar(AData, SizeOf(AData), #0);
25 if ReadSocket(FSocket[FBindIndex], AData) then
26 PostMessage(Application.MainForm.Handle, WM_THREAD_MSG, 0, Longint(@PDataPack));
27
28 Sleep(FWaitTime);
29 except on E: Exception do
30 WriteLog(g_ProLogFile, E.Message);
31 end;
32 end;
33
34end;
35procedure TMainForm.WMThread_msg(var Msg: TMessage);
36var
37 Data: PDataPack;
38begin
39 Data := PDataPack(Msg.lParam);
40 if Data <> nil then
41 begin
42 //TODO: 处理数据
43 end;
44end;