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;