#Confusing thread behavior with mutexes

1 messages · Page 1 of 1 (latest)

median nebula
#

Hello, I don't do much multithreaded programming so I'm a confused on the behavior of the below program.

package main

import "core:thread"
import "core:sync"
import "core:time"
import "core:fmt"

main :: proc() {
    mutex: sync.Mutex
    thread.create_and_start_with_data(&mutex, side_thread)
    
    i := 0

    for {
        sync.mutex_lock(&mutex)
        
        fmt.println("main:", i)
        i += 1
        time.sleep(time.Duration(time.Second))
        
        sync.mutex_unlock(&mutex)
    }
}

side_thread :: proc(data: rawptr) {
    mutex := transmute(^sync.Mutex) data

    i := 0

    for {
        sync.mutex_lock(mutex)
        
        fmt.println("side:", i)
        i += 1
        time.sleep(time.Duration(time.Second))
        
        sync.mutex_unlock(mutex)
    }
}

This will print out the following.

main: 0
main: 1
main: 2
main: 3
main: 4
main: 5
main: 6
main: 7
main: 8
main: 9
main: 10
etc...

I don't understand how the main thread is able to fully block the side thread.

If the mutex is being locked on the main thread first, then the side threads calls mutex_lock() according to the documentation the side thread should then be able to go once mutex_unlock() is called on the main thread.

When the main thread has the mutex locked, and the side thread calls mutex_lock(), does the side thread enter into some type of polling loop where it sleeps for a bit then wakes up and checks if the mutex has been released? Maybe the main thread is just unlocking and locking the mutex during this sleep time? That would explain why the side thread never has a chance to go.

What's going on here? How can I grantee that a waiting thread will proceed once the mutex is unlocked?

heady fulcrum
#

the standard mutex is unfair, meaning it'll only let active threads acquire the lock first. basically it works in a first come first serve sort-a way.
if you unlocked before sleeping there'll be enough time for both threads to acquire the lock.

#

a Ticket_Mutex on the other hand is fair & will hand out the lock in the order the requests come in.

median nebula
#

That makes sense, thanks.