gpt4 book ai didi

concurrency - Go 中互斥锁的问题

转载 作者:IT王子 更新时间:2023-10-29 02:34:07 24 4
gpt4 key购买 nike

除了互斥量之外,一切都很好。在我锁定和解锁后,它不会做任何事情。有什么明显的我想念的吗?

最重要的是,解锁后,我想在这个函数中运行一个函数。我试过将其作为常规函数调用 (timer()) 甚至 (go timer())。

func shield(state *State){
for s := range state.ToggleShield { //run if data on channel
if s == true { //if data on channel is true
fmt.Println("Opening the shields This is uninteruptable. Please wait...")

state.VariableMutex.Lock()
state.Finished = false //disable other commands
state.VariableMutex.Unlock()

fmt.Println("Move!!")
ticker := time.Tick(time.Second)
for i := 10; i >= 0; i-- {
<-ticker
fmt.Printf("\rOn 10/%d", i)
}
}
}
}

最佳答案

The Go Programming Language Specification

Go statements

A "go" statement starts the execution of a function call as an independent concurrent thread of control, or goroutine, within the same address space.

The function value and parameters are evaluated as usual in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. Instead, the function begins executing independently in a new goroutine. When the function terminates, its goroutine also terminates.

您的程序似乎没有适当的机制来等待您的 goroutines 完成:“程序执行不会等待调用的函数完成。”为了证明这一点,我在程序 main 函数的末尾插入了一个粗略的等待机制:

// wait for a while to give goroutines a chance to complete
time.Sleep(5 * time.Second)

程序:https://play.golang.org/p/ODdEihip4m

输出:

Toggling Shield
Opening the shields This is uninteruptable. Please wait...
Move!!

On 10/10
On 10/9
On 10/8
On 10/7
On 10/6

Program exited.

关于concurrency - Go 中互斥锁的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29576950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com