Concurrent Basic初现Visual Basic未来发展端倪。虽然它建立在C#在研语言例如Polyphonic C#和C-Omega的工作基础之上,然而,Visual Basic之所以对其青眼有加,还是在于它具备声明式编程的固有特征。VB的声明式事件处理器激发了这一语法灵感。
关键字
下面是使用这些关键字实现的完整示例,它定义了一个线程安全的缓冲区Buffer。
Class Buffer(Of T) Asynchronous Sub Put (t as T) Synchronous Function Take() as T Function React (t as T) as T When Put, Take Return T End Function End Class
函数Put可以被用户异步调用。Take函数在调用时会阻塞线程,直到最后一项被Put取出。React函数处理的实现细节是通过Put将队列中的对象转换为Take所期望的形式。
下面是两个更复杂的示例。第一个示例会等待A或者B上的一条消息。第二个示例则等待A和B都有消息时才终止。
Class Either(Of T) Asynchronous Sub PutA(t as T) Asynchronous Sub PutB(t as T) Synchronous Function TakeEither() as T Function ReactA(t as T) as T When TakeEither, PutA Return T End Function Function ReactB(t as T) as T When TakeEither, PutB Return T End Function End Class Class Both(Of T, U) Asynchronous Sub PutA(t as T) Asynchronous Sub PutB(u of U) Synchronous Function TakeBoth() as T Function React(t as T, u as U) as Pair(Of T, U) When Take, PutA, PutB Return new Pair(Of T, U)(t, u) End Function End Class
下面的例子是一种单位置缓冲(one place buffer)模式,这种缓存每次最多只能存储一条消息。
Class OPB(of T) Sub New Empty() End Sub Synchronous Sub Put (t as T) Synchronous Function Take() as T Private Asynchronous Empty() Private Asynchronous Full(of T) Sub PutAndEmpty(t as T) When Put, Empty Full(t) End Sub Sub TakeAndFull(t as T) as T When Take, Full Empty() Return t End Sub End Class
如果深入分析,Put、Take、Empty与Full函数均体现了内部队列。执行相关的React方法则是通过对When子句与队列大小进行模式匹配。
迄今给出的示例均假定Take方法是同步的。然而这却并非必然,你也可以使用回调。
Class AsyncBuffer(Of T) Asynchronous Sub Put (t as T) Asynchronous Function Take() as T Function React (callback as Func(t as T), t as T) as T When Put, Take Return callback(t) End Function End Class
使用该方法时,将引发一个线程执行React和回调方法。某些开发人员可能需要执行其他工作,例如使用一个线程池、GUI线程或者其他线程库。为此,你需要实现ContinuationAttribute。以下是该特性的定义。
Public MustInherit Class ContinuationAttribute Inherits Attribute Public MustOverride Sub BeginInvoke( task As Continuation) Public MustOverride Sub Invoke( task As Continuation) End Class Public Delegate Sub Continuation()
示例与用法
Public Class MyThreadPoolAttribute Inherits ContinuationAttribute Public Overrides Sub BeginInvoke( task As Continuation) ThreadPool.Enqueue(task) End Sub Public Overrides Sub Invoke( task As Continuation) task() End Sub End ClassClass AsyncBuffer(Of T)
Asynchronous Sub Put (t as T)
Asynchronous Function Take() as T
Function React (callback as Func(t as T), t as T) as T When Put, Take
Return callback(t)
End Function
End Class
更多信息可以观看Channel 9的视频以及阅读文档Concurrent Basic的提议。
查看英文原文:Concurrent Basic – A Declarative Language for Message-Based Concurrency.