多線程臨界區Demo

var
  iCount: integer = 0;
  iThread: integer = 0; //線程計數
  THreadID: Cardinal;
  CS: TRTLCriticalSection;    //線程臨界區
  hThread:tHlandle;
function myThreaFunc(p: Pointer): DWORD; stdcall;
var
  i: Integer;
begin
  inc(iCount);
  inc(iThread);  //創建一個線程增1
  EnterCriticalSection(cs);
  Form1.mmo1.Lines.Add('i''m  "' + inttostr(iCount) + 'th" Thread');
  for i := iCount to 1000 do
    Form1.mmo1.Lines.Add(IntToStr(i));
  LeaveCriticalSection(Cs);
  dec(iThread); //退出當前線程減1
  CloseHandle(hThread);
  Result := 0;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if iThread < 4 then     //判斷當前開啓線程數
  begin
    hThread:=CreateThread(nil, 0, @mythreaFunc, nil, 0, THreadID);
  end
  else
  begin
    Button1.Caption := IntToStr(iThread);
    Button1.Enabled := False;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  InitializeCriticalSection(cs);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  DeleteCriticalSection(CS);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  ShowMessageFmt('%D個線程在運行', [iThread]);
end;

發佈了216 篇原創文章 · 獲贊 15 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章