英文:
Go Threads - STOP Execution
问题
我有两个goroutine,如下所示:
例程1 {
// 做一些事情
}
例程2 {
// 做一些事情
}
主函数 {
// 做一些事情
}
在例程1中,如果满足某个条件,是否可以停止整个程序的执行?停止主函数和例程2的执行?可以给一个简单的例子吗?
英文:
I have two goroutine like,
Routine 1 {
// do something
}
Routine 2 {
// do something
}
main {
// do something
}
Is it possible from in routine 1, if some condition met, stop whole program execution ? Stop execution of main and Routine 2 ? Can give a simple example.
答案1
得分: 3
例如,
package main
import "os"
func routine1() {
// 当准备退出时,设置 exit = true
exit := false
if exit {
os.Exit(0)
}
}
func routine2() {
}
func main() {
go routine1()
go routine2()
}
英文:
For example,
package main
import "os"
func routine1() {
// set exit = true when ready to exit
exit := false
if exit {
os.Exit(0)
}
}
func routine2() {
}
func main() {
go routine1()
go routine2()
}
答案2
得分: 1
你也可以使用一个通道来让routine1与routine2进行通信。不失一般性,假设routine1向通道发送一些内容,而routine2可以使用select语句从该通道中取出内容,或者从另一个“工作”通道(即为routine提供工作的通道)中取出内容。当routine2从“终止执行”通道中取出内容时,它可以完成剩余的工作并调用os.Exit(0)。
英文:
You could also use a channel to have routine1 communicate with routine2. WLOG routine1 could send something down the channel and routine2 could use a select statement to either take something off of that channel or something off of another "work" channel (a channel that provides work to the routine). When routine2 takes something off of the "kill execution" channel, it could finish up and call os.Exit(0).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论