Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go 用文件实现一个跨进程的 Mutex #6

Closed
binderclip opened this issue Jan 12, 2022 · 0 comments
Closed

Go 用文件实现一个跨进程的 Mutex #6

binderclip opened this issue Jan 12, 2022 · 0 comments
Labels

Comments

@binderclip
Copy link
Owner

需求:

  1. 进程内部可以实现 Mutex
  2. 跨进程也可以实现 Mutex

可参考的:

package lockedfile_sp

import (
	"fmt"
	"sync"
	"testing"
	"time"

	"github.com/rogpeppe/go-internal/lockedfile"
)

func TestLockedfileMutex(t *testing.T) {
	begin := time.Now()
	fmt.Println("start")
	mutex := lockedfile.MutexAt("/tmp/hello")

	wg := sync.WaitGroup{}

	wg.Add(2)
	go func() {
		defer wg.Done()
		unlock, err := mutex.Lock()
		if err != nil {
			panic(err)
		}
		defer unlock()

		fmt.Println("a", time.Since(begin))
		time.Sleep(time.Second * 3)
	}()

	go func() {
		defer wg.Done()
		unlock, err := mutex.Lock()
		if err != nil {
			panic(err)
		}
		defer unlock()

		fmt.Println("b", time.Since(begin))
		time.Sleep(time.Second * 3)
	}()

	wg.Wait()
	fmt.Println("end", time.Since(begin))
}

单进程执行:

start
a 267.708µs
b 3.001576625s
end 6.002901375s

多进程执行:

start
b 79.042µs
a 3.001326792s
end 6.002688917s

start
b 5.688241458s
a 8.689420375s
end 11.690721417s
Repository owner locked and limited conversation to collaborators Aug 17, 2022
@binderclip binderclip converted this issue into discussion #50 Aug 17, 2022

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
Projects
None yet
Development

No branches or pull requests

1 participant