CnPack Open Source Projects - 在Delphi XE中使用go语言的并发编程方法之Demo3
     Home Page    News    Downloads    Nightly Build    Documents    Foundation    Forum    Credits    简体中文
 Latest Releases

 
CnWizards 1.5.0.1209
[2024-09-17]

 
CnVCL 20240917
[2024-09-17]

 
CVSTracNT V2.0.1 Build 20080601
[2008-06-02]
  Nightly Build RSS
  Timeline RSS RSS
 Project Links
CnPack at GitHub
Use GitHub
CnPack Mail
 Visitors
Today Visitors: 189
Today Pages: 1019
Total Visitors: 5256158
Total Pages: 21136084
Since: 2003-09-01
在Delphi XE中使用go语言的并发编程方法之Demo3

CnPack Open Source Projects 2010-12-12 20:26:23

在delphi中使用go语言的并发编程方法,增加demo3
作者:早安·空气

这个例子演示了如何实现超时控制

program demo3;

{$APPTYPE CONSOLE}

uses
  SysUtils,Generics.Collections,
  coroutineUnit;

//这个例子演示了如何实现超时控制

var
    cWork, cTimeout: CChannel<Integer>; //声明两个通道,各用于工作和超时
    ret: tpair<Integer, Integer>; //后面有讲到
begin
cWork:=CChannel<Integer>.create;
cTimeout:=CChannel<Integer>.create;

go(procedure() //起动工作线程
    var
        i: Integer;
    begin
    sleep(1010);  //假设这个工作费时1010毫秒
    try
        cWork.value:=1;  //发通道发送一个值,表示工作完成了。
    except
        end;
    end);

go(procedure()  //起动一个线程用来计时
    begin
    sleep(1000);  //假设超时等待时间是1秒
    cTimeout.value:=1000; //...
    end);

{直到cWork,cTimeout这两个通道至少有一个可读取,获取通道的结果,结果是个pair,其中key描述了哪个通道有响应,value描述了通道的值(对这个select的模仿远没有go语言的幽雅,也许以后会有更好的办法)}
ret:=CCoroutine.select<Integer>([cWork, cTimeout]);  
case ret.key of  //判断是哪个通道可读
    0:    Writeln('完成');  //如果是第0个,就是cWork的信号了,表示在超时等待之前工作完成了。
    1:    Writeln('超时'+inttostr(ret.value));  //...
    end;

cWork.Free;
cTimeout.Free;
Readln;
end.

注:coroutineUnit.pas请见上一篇文章的附件。


Downloads:
在Delphi XE中使用go语言的并发编程方法的例子之三 (4110 times)

Page hits: 19066 times
From: CnPack Open Source Projects

Previous | UpNext

Links:


(C)Copyright 2001-2014 CnPack Develop Team  Site author: JingYu Zhou