GPars(1):入门

随着并行计算在计算机上的广泛应用(自己用的本本都已经是双核的了),并行计算软件也逐步走向台前,GPars就为我们用Groovy编写并行程序提供了方便。在这一GPars系列里将陆续提供GPars 0.9的参考手册要点,希望能给感兴趣的读者提供帮助。

简介

GParApache 2 License)是为Groovy提供的一款开源并行类库,给我们提供了多种高级抽象,包括:map/reduce、fork/join、asynchronous closures、actors、agents、dataflow concurrency及其它概念。这样用Groovy编写并行程序就方便多了。

下载和安装

Groovy的lib目录下带有gpars的类库,如需下载,GPars0.9的各资源链接如下:

Hello World

下面这个例子是用actor实现的,其功能描述请阅读代码前的说明。至于actor的相关介绍则会出现在以后的文章中。

import static groovyx.gpars.actor.Actors.actor
/**
 * A demo showing two cooperating actors. The decryptor decrypts received 
 * messages and replies them back. The console actor sends a message to 
 * decrypt, prints out the reply and terminates both actors.
 * The main thread waits on both actors to finish using the join() method 
 * to prevent premature exit, since both actors use the default actor group,
 * which uses a daemon thread pool.
 * @author Dierk Koenig, Vaclav Pech
 */
 def decryptor = actor {
    //循环接收消息
    loop {
        react {message ->
            //如果消息是字符串,则倒置并作为消息回送;否则,停止actor
            if (message instanceof String) reply message.reverse()
            else stop()
        }
    }
}
def console = actor {
    //给decryptor这一actor发送一个字符串消息
    decryptor.send 'lellarap si yvoorG'
    //接收一条消息(本例只可能接收decryptor送回的消息)
    react {
        //打印接收到的消息,然后在向decryptor发出false类型的消息(告知
        //decryptor终止)
        println 'Decrypted message: ' + it
        decryptor.send false
    }
}

//下面写法表示等待多个actors结束。
[decryptor, console]*.join()

执行这段代码的结果是“Decrypted message: Groovy is parallel”。 代码中stop()发送消息以终止decryptor,该actor终止之前会处理完队列中的消息。与之功能相仿的还有另一方法terminate(),它则直接终止actor,未处理的消息被传递给afterStop方法做后续处理。

参考资料:

GPare用户指南

By songwei - Posted on 26 二月 2010