我有两个并发的go例程,如下所示
Routine 1{
routine procedure
critical section{
}
routine procedure
}
Routine 2{
routine procedure
critical section{
}
routine procedure
} 是否可以使用一些go内置函数来实现临界区?
发布于 2011-11-28 20:15:03
你的问题:
i有N个并发go例程(都有或多或少相同的目的)。其中每一个都有一个关键部分。在进入临界区之前,每个例程只做一些消息发送工作。当它进入临界区时,我需要所有其他例程必须停止执行,直到它退出临界区。在GO中使用任何库函数是可能的吗?
您所询问的(当一个goroutine处于临界区时,强制停止所有其他goroutine)在Go程序中并不典型。没有可以停止所有其他goroutines的库函数,所以您需要通过在程序中的goroutines之间设计适当的同步来停止它们。典型的场景是所有goroutines (潜在地)并发运行,除了那些因为某种原因被阻塞的goroutines。
要控制对Go程序中共享资源的并发访问,可以使用Go通道、"sync"包、管道或网络连接。
使用sync.Mutex,Go代码可能看起来像这样(但请记住,只要有可能,Go程序最好使用Go通道而不是互斥):
package main
import "sync"
var m sync.Mutex
var wg sync.WaitGroup
func routine1() {
... do something ...
m.Lock()
... critical section (access the shared resource here) ...
m.Unlock()
... do something ...
wg.Done()
}
func routine2() {
... do something ...
m.Lock()
... critical section (access the shared resource here) ...
m.Unlock()
... do something ...
wg.Done()
}
func main() {
wg.Add(1); go routine1()
wg.Add(1); go routine2()
wg.Wait()
}发布于 2011-11-28 00:11:06
您可以尝试使用缓冲通道:
c := make(chan int, 2)这将在实际发送之前缓冲发送的数据。
发布于 2011-11-28 00:50:55
你是说像这样的东西吗?
package main
import "fmt"
func ping(recv <-chan int, send chan<- int, end chan<- bool) {
fmt.Println("ping")
send <- 11
send <- 12
r1 := <-recv
r2 := <-recv
fmt.Println("ping", r1, r2)
end <- true
}
func pong(recv <-chan int, send chan<- int, end chan<- bool) {
fmt.Println("pong")
r1 := <-recv
r2 := <-recv
send <- 21
send <- 22
fmt.Println("pong", r1, r2)
end <- true
}
func main() {
chEnd := make(chan bool)
chPing := make(chan int, 2)
chPong := make(chan int, 2)
go ping(chPing, chPong, chEnd)
go pong(chPong, chPing, chEnd)
<-chEnd
<-chEnd
fmt.Println("end")
}输出:
ping
pong
pong 11 12
ping 21 22
endhttps://stackoverflow.com/questions/8286806
复制相似问题