More Related Content Similar to ジャパネットQB GPars Similar to ジャパネットQB GPars (20) ジャパネットQB GPars28. 並列コレクション
import static groovyx.gpars.GParsPool.withPool
def nums = 1..100000
withPool(5) {
def squares = nums.
collectParallel{ it ** 2 }.
grepParallel{ it % 7 == it % 5 }.
grepParallel{ it % 3 == 0 }
println squares[0..3] + "..." + squares[-3..-1]
assert squares[0..3] == [36, 144, 1089, 1296]
}
30. 並列コレクション
import static groovyx.gpars.GParsPool.withPool
def nums = 1..100000
withPool(5) {
def squares = nums.parallel.
map{ it ** 2 }.
filter{ it % 7 == it % 5 }.
filter{ it % 3 == 0 }.
collection
println squares[0..3] + "..." + squares[-3..-1]
assert squares[0..3] == [36, 144, 1089, 1296]
}
32. Fork/Join
import static groovyx.gpars.GParsPool.withPool
import static groovyx.gpars.GParsPool.runForkJoin
def quicksort(numbers) {
withPool {
runForkJoin(0, numbers) {index, list ->
def groups = list.groupBy {
it <=> list[list.size().intdiv(2)]}
if ((list.size() < 2) || (groups.size() == 1)) {
return [index: index, list: list.clone()]
}
(-1..1).each {
forkOffChild(it, groups[it] ?: [])}
return [index: index,
list: childrenResults.sort
{it.index}.sum {it.list}]
}.list
}
}
37. 次は、Agent。
オブジェクトに
スレッドセーフにアクセスするための
仕組みだよ。
38. Agent
import static groovyx.gpars.agent.Agent
def jugMembers = new Agent<List<String>>(['Me'])
jugMembers.send {it.add 'James'}
final Thread t1 = Thread.start {
jugMembers << {it.add 'Joe'}
}
final Thread t2 = Thread.start {
jugMembers {it.add 'Dave'}
jugMembers {it.add 'Alice'}
}
[t1, t2]*.join()
println jugMembers.val
jugMembers.valAsync {println "Current members: $it"}
jugMembers.await()