go 类型和点语法是什么

问题描述 投票:0回答:1

dmeo 代码

package listing12_9

import (
    "runtime"
    "sync"
    "sync/atomic"
)

type SpinLock int32

func (s *SpinLock) Lock() {
    for !atomic.CompareAndSwapInt32((*int32)(s), 0, 1) {
        runtime.Gosched()
    }
}

func (s *SpinLock) Unlock() {
    atomic.StoreInt32((*int32)(s), 0)
}

func NewSpinLock() sync.Locker {
    var lock SpinLock
    return &lock
}

atomic.CompareAndSwapInt32((*int32)(s), 0, 1)
语法是什么,(*int) 和 (s) 是什么意思?

go type-conversion
1个回答
0
投票

您已在此处定义了类型:

type SpinLock int32

但是您将使用此规范调用原子包中的方法:

func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)

所以要将类型为SpinLock的变量s发送到CompareAndSwapInt32方法,你必须告诉编译器s可以用作int32,这称为类型转换,在golang中我们这样做这种工作是这样的:

convertedValue := TargetType(variable)

但是在 Learn ConcurrentProgramming with Go 书中它使用了将变量 s 从类型 *SpinLock 转换为 *int32 的老式方法,更现代的方法可能是:

type SpinLock int32

func (s SpinLock) Lock() {
    castedS := int32(s)
    for !atomic.CompareAndSwapInt32(&castedS, 0, 1) {
        runtime.Gosched()
    }
}

func (s SpinLock) Unlock() {
    castedS := int32(s)
    atomic.StoreInt32(&castedS, 0)
    atomic.StoreInt32(&castedS, 0)
}
© www.soinside.com 2019 - 2024. All rights reserved.