Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/prodemmi/golang-mutex
How to work with go mutex
https://github.com/prodemmi/golang-mutex
Last synced: 12 days ago
JSON representation
How to work with go mutex
- Host: GitHub
- URL: https://github.com/prodemmi/golang-mutex
- Owner: prodemmi
- Created: 2024-01-24T11:49:46.000Z (12 months ago)
- Default Branch: main
- Last Pushed: 2024-01-24T11:51:57.000Z (12 months ago)
- Last Synced: 2024-11-07T13:46:26.036Z (2 months ago)
- Size: 1.95 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# golang-mutex
How to work with go mutex```go
package mainimport (
"fmt"
"sync"
)type Memory[T any] struct {
Data []T
Mutex sync.Mutex
}func NewMemory[T any]() (*Memory[T], error) {
mem := Memory[T]{
Data: make([]T, 0),
}
return &mem, nil
}func (mem *Memory[T]) Append(data T) {
mem.Mutex.Lock()
mem.Data = append(mem.Data, data)
mem.Mutex.Unlock()
}
func (mem *Memory[T]) Display() {
for _, item := range mem.Data {
fmt.Println(item)
}
}func main() {
memory, _ := NewMemory[string]()
terminator := make(chan string, 0)
runner := func(procId string, mem *Memory[string]) {
defer func() {
terminator <- ""
}()for i := 0; i < 5; i++ {
item := fmt.Sprintf("PID[%s]: %d", procId, i)
mem.Append(item)
}
}go runner("1", memory)
go runner("2", memory)
go runner("3", memory)j := 0
for {
if j >= 3 {
break
}select {
case _ = <-terminator:
j++
}
}memory.Display()
```