程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> 多線程編程(19) - 不使用同步工具,手動協調線程依次執行(2)

多線程編程(19) - 不使用同步工具,手動協調線程依次執行(2)

編輯:Delphi

第一個例子的代碼文件(窗體同上):

unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
PaintBox1: TPaintBox;
PaintBox2: TPaintBox;
PaintBox3: TPaintBox;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
const
colors: array[0..2] of TColor = (clRed, clGreen, clBlue);
var
hArr: array[0..2] of THandle;
panitArr: array[0..2] of TPaintBox;
hMutex: THandle; {互斥對象的句柄}
function ThreadFun(p: Pointer): Integer; stdcall;
var
i,n,x1,y1,x2,y2: Integer;
begin
n := Integer(p);
panitArr[n].Color := colors[n];
if WaitForSingleObject(hMutex, INFINITE) = WAIT_OBJECT_0 then
begin
for i := 0 to 50 do with panitArr[n] do
begin
x1 := Random(Width); y1 := Random(Height);
x2 := Random(Width); y2 := Random(Height);
Canvas.Lock;
Canvas.Ellipse(x1,y1,x2,y2);
Canvas.Unlock;
Sleep(10);
end;
ReleaseMutex(hMutex);
end;
Result := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ID: DWord;
i: Integer;
begin
panitArr[0] := PaintBox1;
panitArr[1] := PaintBox2;
panitArr[2] := PaintBox3;
CloseHandle(hMutex);
hMutex := CreateMutex(nil, False, nil);
for i := 0 to Length(hArr) - 1 do
hArr[i] := CreateThread(nil, 0, @ThreadFun, Ptr(i), 0, ID);
end;
procedure TForm1.FormDestroy(Sender: TObject);
var
i: Integer;
begin
CloseHandle(hMutex);
for i := 0 to Length(hArr) - 1 do CloseHandle(hArr[i]);
end;
end.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved