Created
February 10, 2021 09:06
-
-
Save gekigek99/23e301e0325f455780ceb6a3629ff458 to your computer and use it in GitHub Desktop.
function to execute entire functions with a locked mutex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this script can be use to execute entire functions with a locked mutex. | |
// It is especially useful when a if statement needs to read from a mutex sensible variable. | |
// withLock accepts either a "func()" or a "func() interface{}" | |
// in the first case, it executes the function returining <nil> | |
// in the second case, it returns the value of the function as an interface{} | |
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
var m = &sync.Mutex{} | |
var wg sync.WaitGroup | |
var tot int | |
var totlock int | |
func main() { | |
for n := 0; n < 10000; n++ { | |
wg.Add(2) | |
go func() { tot++; wg.Done() }() | |
go withLock(func() { totlock++; wg.Done() }) | |
} | |
fmt.Println("without lock:\t", tot) | |
fmt.Println("with lock:\t", totlock) | |
// prints true | |
fmt.Println(withLock(func() interface{} { return 1 == 1 })) | |
// prints hello | |
fmt.Println(withLock(func() interface{} { return "hello" })) | |
// use as conditional | |
if withLock(func() interface{} { return 1 == 1 }).(bool) { | |
fmt.Println("if block") | |
} | |
// prints <nil> | |
fmt.Println(withLock(func() bool { return false })) | |
fmt.Println(withLock(func() (interface{}, interface{}) { return "a", "b" })) | |
} | |
func withLock(i interface{}) interface{} { | |
m.Lock() | |
defer m.Unlock() | |
switch i.(type) { | |
case func(): | |
i.(func())() | |
case func() interface{}: | |
return i.(func() interface{})() | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment