在写多线程下sleep的功能,能否详细一点

解决方案 »

  1.   

    一个需要用线程同步来解决的问题。假设有一个整数数组,需要按升序赋初值。
    现在要在第一遍把这个数组赋初值为1至1 2 8,第二遍将此数组赋初值为1 2 8至2 5 5,
    然后结果显示在列表框中。要用两个线程来分别进行初始化。
    源码如下:
    //////////////////////////////////////////////////////////////////
    unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
      StdCtrls;type
      TMainForm = class(TForm)
        Button1: TButton;
        ListBox1: TListBox;
        Button2: TButton;
        procedure Button1Click(Sender: TObject);
        procedure Button2Click(Sender: TObject);
      private
        procedure ThreadsDone(Sender: TObject);
        { Private declarations }
      public
        { Public declarations }
      end;  TFOOThread = class(TThread)
      protected
        procedure Execute; override;
      end;var
      MainForm: TMainForm;implementation{$R *.DFM}
    const
      MaxSize = 128;var
      NextNumber: Integer = 0;
      DoneFlags:  Integer = 0;
      GlobalArray: array [1..MaxSize] of Integer;
      CS : TRTLCriticalSection;function GetNextNumber: Integer;
    begin
      Result := NextNumber; // return global var
      Inc(NextNumber);      //inc global var
    end;procedure TMainForm.Button1Click(Sender: TObject);
    begin
      initializeCriticalSection(CS);
      TFooThread.Create(False);  //create threads
      TFooThread.Create(False);
    end;{ TFOOThread }procedure TFOOThread.Execute;
    var
      i: Integer;
    begin
      OnTerminate := MainForm.ThreadsDone;
      EnterCriticalSection(CS);
      for i := 1 to MaxSize  do
      begin
        GlobalArray[i] := GetNextNumber;   //set array element
        Sleep(5);                          //这句话干什么?
      end;
      LeaveCriticalSection(CS);
    end;
    procedure TMainForm.ThreadsDone(Sender: TObject);
    var
      i : Integer;
    begin
      
      inc(DoneFlags);
      if DoneFlags = 2 then  //make sure both threads finished
        for i := 1 to MaxSize do
          {fill listbox with array contents}
          ListBox1.Items.Add(IntToStr(GlobalArray[i]));
      DeleteCriticalSection(CS);
    end;procedure TMainForm.Button2Click(Sender: TObject);
    begin
      Button2.caption := IntToStr(GetNextNumber);
      MainForm.Caption:=IntToStr(ListBox1.Items.Count);
    end;end.
      

  2.   

    Sleep就语句本身来说的话
    就是告诉cpu当前不要为他分配时间片,这样其他的线程就有机会执行了
    因为一共有三个线程(包括主进程),由于你使用了临界区,代码区实际的执行线程只会有一个,呵呵。《delphi开发人员指南》11章中讲得很详细,可以参考一下
      

  3.   

    TO: basboy(basboy) 
    我就是在《delphi开发人员指南》11章中
    看不懂才来这里问