登录
首页 >  Golang >  Go问答

使用Go语言实现自动锁定/解锁的方法

来源:stackoverflow

时间:2024-02-05 21:54:19 324浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《使用Go语言实现自动锁定/解锁的方法》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我有一个包含许多“公共”方法的结构,我需要保持线程安全。

package main

import "sync"

type Test struct {
    sync.Mutex
    privateInt    int
    privateString string
    privateMap    map[string]interface{}
}

func (p *Test) A() {
    p.Lock()
    defer p.Unlock()

    // do something that changes the fields...
}

func (p *Test) B() {
    p.Lock()
    defer p.Unlock()

    // do something that changes the fields...
}

func (p *Test) C() {
    p.Lock()
    defer p.Unlock()

    // do something that changes the fields...
}

func (p *Test) D() {
    p.Lock()
    defer p.Unlock()

    // do something that changes the fields...
}

// and so on

如果结构体有很多方法,我必须检查并确认每个方法都执行锁定。 看起来有点蠢。


正确答案


我想到了一种类似数据库的方式。 我用另一个 struct testprovider 包装了 struct test,并且在使用 test 之前必须调用 transaction() 来获取指针。

package main

import "sync"

type Test struct {
    privateInt    int
    privateString string
    privateMap    map[string]interface{}
}

func (p *Test) A() {
    // do something that changes the fields...
}

func (p *Test) B() {
    // do something that changes the fields...
}

func (p *Test) C() {
    // do something that changes the fields...
}

func (p *Test) D() {
    // do something that changes the fields...
}

// and so on

type TestProvider struct {
    sync.Mutex
    test *Test
}

func (p *TestProvider) Transaction(callback func(test *Test)) {
    p.Lock()
    defer p.Unlock()
    callback(p.test)
}

func NewTestProvider(test *Test) *TestProvider {
    return &TestProvider{
        test: test,
    }
}

func main() {
    p := NewTestProvider(&Test{})
    go p.Transaction(func(test *Test) {
        test.A()
        test.B()
    })
    go p.Transaction(func(test *Test) {
        test.C()
        test.D()
    })
}

效果很好,但我认为可能有更好的方法。

以上就是《使用Go语言实现自动锁定/解锁的方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>