Pikapops
Pikapops

Reputation: 741

Problems with Mutex Locking in Go

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("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)
            }
        }
    }
}

Upvotes: 0

Views: 2069

Answers (1)

peterSO
peterSO

Reputation: 166895

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.

Upvotes: 4

Related Questions