Delphi 利用信号变量实现多进程之间排队同步
核心代码:
var
Form1: TForm1;
hSem :THandle=0;
const
SEMAPHORE_ALL_ACCESS=STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $3;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(IntToStr(hSem));
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
hSem:=OpenSemaphore(SEMAPHORE_ALL_ACCESS, True, 'YXTest');
Memo1.Lines.Add(IntToStr(hSem));
end;
procedure TForm1.FormShow(Sender: TObject);
begin
hSem:=OpenSemaphore(SEMAPHORE_ALL_ACCESS, True, 'YXTest');
if hSem=0 then
hSem:=CreateSemaphore(nil,1,1,'YXTest');
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ReleaseSemaphore(hSem,1,nil);
CloseHandle(hSem);
end;
//线程函数
function test(P: pointer): Longint; stdcall;
var
currentTime:TSystemTime;
year, month, day, hour, minute, second, millisecond: string;
datetime: string;
begin
while true do
begin
//等待信号值为非0
WaitForSingleObject(hSem, INFINITE);
GetSystemTime(currentTime);
year:= IntToStr(currentTime.wYear);
month:= IntToStr(currentTime.wMonth);
day:= IntToStr(currentTime.wDay);
hour:= IntToStr(currentTime.wHour + 8);
minute:= IntToStr(currentTime.wMinute);
second:= IntToStr(currentTime.wSecond);
millisecond:= IntToStr(currentTime.wMilliseconds);
datetime:= year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second + ':' + millisecond;
Form1.Memo1.Lines.Add(datetime);
Sleep(500);
ReleaseSemaphore(hSem,1,nil);
end;
end;
//创建线程
procedure TForm1.Button3Click(Sender: TObject);
var
ThreadID: DWORD;
begin
CreateThread(nil, 0, @test, nil, 0, ThreadID);
end;
如果觉得文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
作者:YXGust
出处:https://www.cnblogs.com/YXGust/p/14682396.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
本博文版权归本博主所有,转载请注明原文链接