【问题标题】:Multithread interactions多线程交互
【发布时间】:2015-07-27 09:44:05
【问题描述】:

主窗体:

unit Unit3;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm3 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    class var counter : Integer;
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}

uses Unit4, Unit5;

procedure TForm3.Button1Click(Sender: TObject);
var
  th1 : thCounter;
  th2 : thPrinter;
begin
  th1:= thCounter.Create;
  th2:= thPrinter.Create;
end;

end.

线程计数器:

unit Unit4;

interface

uses
  System.Classes, Unit3;

type
  thCounter = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
  end;

implementation

{ thCounter }

procedure thCounter.Execute;
var
  i: Integer;
  printVal : Integer;
begin
  { Place thread code here }
  printVal:= 50;
  for i := 0 to 1000000000 do
  begin
    Form3.counter:= i;
    if Form3.counter = printVal then
    begin
      // RUN print thread    ????
      printVal:= printVal + 50;
    end;
  end;
end;

end.

线程打印:

unit Unit5;

interface

uses
  System.Classes, Unit3;

type
  thPrinter = class(TThread)
  private
    { Private declarations }
    procedure printIt;
  protected
    procedure Execute; override;
  end;

implementation

uses
  System.SysUtils;

{ thPrinter }

procedure thPrinter.Execute;
begin
  { Place thread code here }
  Synchronize(printIt);
end;

procedure thPrinter.printIt;
begin
  Form3.Memo1.Lines.Add(IntToStr(Form3.counter));
end;

end.

我正在做一个简单的项目。但我卡住了。

我有 2 个线程,即 thCounter 和 thPrint。 My thCounter,将 Counter 增加到 10 亿。我想在计数器 50 和 100、150、200 等倍数时调用另一个线程( thPrint )以在 TMemo 中打印屏幕......

如何从 thCounter 向 thPrint 发送消息?

【问题讨论】:

  • 我没有。谢谢,检查一下:)
  • @Ken 好的,但这不是我的问题:/
  • @Ken 访问类的数据成员很好,没有 VCL/线程问题。该设计令人怀疑,但您指出的问题不适用于此处。
  • @Heart 问题不是读写。问题是窗口的三个亲和性、所有访问(读取和写入)的线程安全以及 MakeObjectInstance 的线程安全。

标签: multithreading delphi


【解决方案1】:

要向其他线程发送信号,请使用同步原语,例如 TSimpleEvent

让它归thCounter线程所有,并在thPrinter创建时传递一个对它的引用。

thPrinter.Execute

while not Terminated do
begin
  if waitEvent.WaitFor(100) = wrSignaled then // Keep it listening to the Terminated flag
  begin
    Synchronize(PrintIt);
  end;
end;

而在thCounter

waitEvent.SetEvent;  // Triggers the printIt 

只需创建 waitEvent 以便在事件触发后自动重置。

waitEvent := TSimpleEvent.Create(nil, false,false,'');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多