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 国际」许可协议进行许可。
本博文版权归本博主所有,转载请注明原文链接
分类:
Delphi 2.编程技巧
标签:
线程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本