droe9376
2014-06-03 07:18在多个线程中运行一个函数
I have implemented a function contractGraph
which calculates a minimal cut of a graph using randomized contraction. I am running it a specified number of times and calculating the minimum cut:
minCut := 0
for i := 0; i < totalCount; i++ {
_minCut := contractGraph(graph)
if minCut == 0 || _minCut < minCut {
minCut = _minCut
}
}
contractGraph
does CPU intensive calculations, but the program uses only one CPU core on my machine. I want to modify it, so at any time 4 parallel executions of contractGraph
happen, the results are put in channel and are read synchronously and the minimum is calculated.
I tried:
func worker(graph Graph, i int, workerChan <- chan bool, minCutChan chan <- int) {
defer func () { <- workerChan }()
min_cut := contractGraph(graph)
minCutChan <- min_cut
}
func workerRunner(graph Graph, minCutChan chan int, totalCount int, workerCount int) {
workerChan := make(chan bool, workerCount)
for i := 0; i < totalCount; i++ {
go worker(graph, i, workerChan, minCutChan)
}
}
minCutChan := make(chan int)
go workerRunner(graph, minCutChan, totalCount, 4)
// read the resulting min cuts
minCut := 0
for _minCut := range minCutChan {
if minCut == 0 || _minCut < minCut {
minCut = _minCut
}
}
But still only one core is used and I get at the end:
fatal error: all goroutines are asleep - deadlock!
Also I don't like having to channels, I think it should be possible to have only one channel with the results.
What pattern would you recommend to use?
- 点赞
- 回答
- 收藏
- 复制链接分享
1条回答
为你推荐
- 垃圾回收器如何回收局部线程对象和判断函数栈里引用对象的
- java
- 1个回答
- python threading多线程的一个小问题。
- python
- 3个回答
- N阶矩阵乘法的并行线程化,创建k个线程,分别计算N/k行,存到同一数组,出错求助(Linux多线程编程)
- c语言
- linux
- c++
- bash
- 2个回答
- Linux死锁多线程编程在qt中运行异常
- c语言
- linux
- c++
- ubuntu
- 1个回答
- Asp.Net MVC,如何让控制器里面函数线程变为STAThread
- 控件
- 异常
- mvc
- asp.net
- 线程
- 3个回答
换一换