我的线程和form都在同一个pas中。form中有一个mscomm控件。我在这个pas中定义了很多类似下面的函数:
procedure CtrlUp();
begin
//抬针
SetControl($FF,C_UP,False);
WaitForSampleCtrlStatus(csUp);
end;
procedure CtrlDown();
begin
//放针
SetControl($FF,C_DOWN,False);
WaitForSampleCtrlStatus(csDown);
end;
procedure CtrlReset();
begin
//复位
SetControl($FF,C_RESET,False);
WaitForSampleCtrlStatus(csReset);
end;
……
其中SetControl中使用了form.mscomm。那么,我的问题是,上面那些函数,我是否可以在线程中直接使用???
procedure CtrlUp();
begin
//抬针
SetControl($FF,C_UP,False);
WaitForSampleCtrlStatus(csUp);
end;
procedure CtrlDown();
begin
//放针
SetControl($FF,C_DOWN,False);
WaitForSampleCtrlStatus(csDown);
end;
procedure CtrlReset();
begin
//复位
SetControl($FF,C_RESET,False);
WaitForSampleCtrlStatus(csReset);
end;
……
其中SetControl中使用了form.mscomm。那么,我的问题是,上面那些函数,我是否可以在线程中直接使用???
Synchronize(CtrlReset);
procedure TMyThread.PushTheButton;begin
Button1.Click();
end;procedure TMyThread.Execute;
begin
...
Synchronize(PushTheButton);
...
end;如果用Synchronize,则里面的函数,一定要在TMyThread中定义一下吗?如果是这样可麻烦了,我有很多上面的类似的函数啊!!!
下面是我的代码constructor TAutoThread.Create(cn : string;ti,ci : integer);
begin
FCasesNo := cn;
FTurntableIndex := ti;
FChannelIndex := ci;
inherited Create(False);
end;
procedure TAutoThread.Execute;
begin
//执行完毕自动释放
FreeOnTerminate := True;
//首先
EnterCriticalSection(csCtrl);
try
//
Synchronize(CtrlTurntable(FTurntableIndex));
finally
LeaveCriticalSection(csCtrl);
end;
end;
Synchronize里面的函数不能带参数!
begin
CtrlTurntable(FTurntableIndex);
end;
constructor TAutoThread.Create(cn : string;ti,ci : integer);
begin
FCasesNo := cn;
FTurntableIndex := ti;
FChannelIndex := ci;
inherited Create(False);
end;
procedure TAutoThread.Execute;
begin
//执行完毕自动释放
FreeOnTerminate := True;
//首先
EnterCriticalSection(csCtrl);
try
//
Synchronize(DOCtrlTurntable);
finally
LeaveCriticalSection(csCtrl);
end;
end;
=======================================================
线程创建和执行
create();
Execute;线程终止
FreeOnTerminate;
OnTerminate;
Terminated;
Terminate;与VCL同步
Synchronize();
消息优先级
Priority;挂起和唤醒
Suspend;
Resume;测试线程时间
GetThreadTimes();线程局部变量
threadvar线程同步
1.临界区
CS: TRTLCriticalSection;
InitializeCriticalSection(CS);
EnterCriticalSection(CS);
LeaveCriticalSection(CS);
DeleteCriticalSection(CS);
2.互斥
hMutex: THandle = 0;
hMutex := CreateMutex(nil, False, nil);
if WaitForSingleObject(hMutex, INFINITE) = WAIT_OBJECT_0 then
ReleaseMutex(hMutex);
CloseHandle(hMutex);
3.信号量
hSem: THandle = 0;
hSem := CreateSemaphore(nil, 1, 1, nil);
if WaitForSingleObject(hSem, INFINITE)= WAIT_OBJECT_0 then
ReleaseSemaphore(hSem, 1, nil);
CloseHandle(hSem);
4.事件