Go线程 – 暂停执行

huangapple go评论117阅读模式
英文:

Go Threads - Pause Execution

问题

我有两个执行线程,像这样,

程序1 {
// 做一些事情
}
程序2 {
// 做一些事情
}

是否可以在程序1中暂停程序2的执行几秒钟,如何实现?

英文:

I have two threads of execution like,

Routine 1 {
// do something
}
Routine 2 {
// do something
}

Is it possible to pause execution of routine 2 from routine 1 for few seconds and how can it possible ?

答案1

得分: 6

无法从一个goroutine控制另一个goroutine的执行。Goroutines是协作的。它们不会互相支配。

你可以在routine 2中设置检查点,检查它是否被允许继续执行。例如:

// 做一些事情
select {
case <-wait:
    <-resume
default:
}

然后,routine 1可以告诉routine 2等待一个信号:

wait <- true
// 这里可以放一些其他的事情
resume <- true

为什么你想要暂停goroutine?这可能有助于更好地回答你的问题。最好从你想要做什么的角度出发,而不是如何做。这样,你可以找到在语言中实现你真正想要的东西的方法,而不是被给予原本想象的实现方法的差劲替代品。

英文:

It is not possible to control the execution of one goroutine from another. Goroutines are cooperative. They don't dominate each other.

What you could do is put points in routine 2 where it checks whether it's allowed to proceed. Such as

// do stuff
select {
case &lt;-wait:
    &lt;-resume
default:
}

Then routine 1 could tell routine 1 could send a signal to routine 2 telling it to wait:

wait &lt;- true
// whatever stuff goes here
resume &lt;- true

Why do you want to pause the goroutine? That might help answer your question better. It is best to start from a place of what you are trying to do rather than how you want to do it. That way, you can find out how to achieve what you actually want in the language, rather than being given poor substitutes for the method of achieving it that you'd originally imagined.

答案2

得分: 1

从一个线程中,无法隐式地控制另一个线程。你可以这样做,定义一个布尔值,根据它来暂停,使用 time.Sleep(2*1e9)。

英文:

From one thread, it is not possible to control another thread implicitly. You can do like this, define a bool and based on that you can pause by time.Sleep(2*1e9).

huangapple
  • 本文由 发表于 2011年12月5日 10:16:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/8380332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定