delphi 协程 doroutine - hellow world

简介

作者长期使用golang、C++,已经习惯了使用协程来分解问题;新的项目需要用到delphi,delphi目前没有提供协程,自己之前有深入研究golang协程源码,所以依据 golang 1.18源码 https://github.com/golang/go/tree/release-branch.go1.18 修改成 delphi 版本;不开源,因为我是欧阳疯,一个疯子,追求天下第一,除了我能练九阴真经外,看过真经的人都得死,我只求天下第一,不缺钱,不图挣钱,故免费使用;

示例代码

只要引入下 doroutine 单元就可以了,引入这个单元后,会有三个变量 供您使用:

  • go 这个变量熟悉吧,就是golang 里的 go fun1()协程,go.bg / go.ui 可以无限分支协程;
  • gt 这个变量中的 t表示 timer的意思,可不是delphi里的timer,这个主要用于分支 重复执行的协程,具体看重复任务那篇博客;
  • gm 这个变量 m表示 manager的意思,可以用户配置 全局异常 和 取消某一个协程,具体看 全局异常 和 协程取消那篇博客;
unit main;

interface

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

type
  TFormMain = class(TForm)
    Memo1: TMemo;
    button1: TButton;
    procedure button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    /// <summary>
    /// 类过程
    /// </summary>
    procedure helloWorld(go: TGo);
  end;

var
  FormMain: TFormMain;

implementation

{$R *.dfm}

/// <summary>
/// 普通过程
/// </summary>
procedure TFormMain.helloWorld(go: TGo);
begin
  Memo1.Lines.Add(Format('hello world,线程ID: %s', [TThread.Current.ThreadID.ToString]));
end;

procedure helloWorld2(go: TGo);
begin
  OutputDebugString(PChar(Format('hello world,线程ID: %s', [TThread.Current.ThreadID.ToString])));
end;

procedure TFormMain.button1Click(Sender: TObject);
begin
  Memo1.Lines.Add(Format('当前主线程的ID:%s', [TThread.Current.ThreadID.ToString]));
  go.ui(helloWorld).start;
  go.bg(helloWorld2).start;
end;

end.

效果图

image

posted @ 2025-02-05 14:03  殴阳疯  阅读(155)  评论(0)    收藏  举报