在Go语言中使用互斥锁的问题

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

Problems with Mutex Locking in Go

问题

除了互斥锁之外,一切都运行得很好。在我锁定和解锁之后,它不会执行任何操作。我是否忽略了一些明显的东西?

除此之外,在解锁之后,我想在这个函数内部运行一个函数。我尝试过像调用普通函数一样调用它(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)
            }
        }
    }
}
英文:

Everything works great apart from the mutex. After I lock and unlock, it won't do anything. Is there something obvious I'm missing?

On top of this, after unlocking, I want to run a function inside this function. I've tried just calling it as a regular function (timer()) and even (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(&quot;Opening the shields This is uninteruptable. Please wait...&quot;)

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

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

答案1

得分: 4

《Go编程语言规范》

Go语言中的"go"语句可以将一个函数调用作为独立的并发线程或goroutine在同一地址空间中启动执行。

在调用goroutine时,函数值和参数会像通常一样在调用的goroutine中进行评估,但与常规调用不同,程序的执行不会等待被调用的函数完成。相反,该函数会在一个新的goroutine中独立开始执行。当函数终止时,它的goroutine也会终止。

你的程序似乎没有适当的机制来等待goroutine完成:"程序的执行不会等待被调用的函数完成"。为了证明这一点,在你的程序的main函数末尾,我插入了一个简单的等待机制:

// 等待一段时间,以便给goroutine完成的机会
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

程序已退出。
英文:

> 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.

Your program does not appear to have proper mechanisms to wait until your goroutines complete: "program execution does not wait for the invoked function to complete." To demonstrate this, I inserted a crude wait mechanism at the end of your program main function:

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

Program: https://play.golang.org/p/ODdEihip4m

Output:

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.

huangapple
  • 本文由 发表于 2015年4月11日 18:42:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/29576950.html
匿名

发表评论

匿名网友

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

确定