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;

posted on 2021-04-20 19:00  YXGust  阅读(253)  评论(0编辑  收藏  举报

导航