go - 如何在 Go 中将 time.Time 变量转换为原子变量?

标签 go atomic

在我的在线游戏 RESTFUL 网络服务中,我将每个问题的开始时间存储在一个全局变量中,如下所示:var MyTime time.Time 我应该在每个级别后更新它游戏的。我的应用程序是分布式的,所以我想确保我的所有应用程序不会同时更新它。这就是为什么我决定让它成为原子的。 其实我很熟悉 Golang sync/atomic 包。 我尝试使用 atomic.LoadPointer() 方法,但它需要不安全的特定参数类型。你还有其他办法吗?

更新: 好的,我这样解决了我的问题。 我将时间变量定义为 atomic.Value 并使用原子加载和存储方法。这是代码: var myTime atomic.Value myTime.Store(newTime) 并加载 myTime.Load().(time.Time)

考虑到 Load() 方法返回接口(interface),所以你应该在最后写 (time.Time) 以便将其转换为 time.Time 类型。

最佳答案

这不能这样做,因为 time.Time是复合类型:

type Time struct {
    // wall and ext encode the wall time seconds, wall time nanoseconds,
    // and optional monotonic clock reading in nanoseconds.
    //
    // From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
    // a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
    // The nanoseconds field is in the range [0, 999999999].
    // If the hasMonotonic bit is 0, then the 33-bit field must be zero
    // and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
    // If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
    // unsigned wall seconds since Jan 1 year 1885, and ext holds a
    // signed 64-bit monotonic clock reading, nanoseconds since process start.
    wall uint64
    ext  int64

    // loc specifies the Location that should be used to
    // determine the minute, hour, month, day, and year
    // that correspond to this Time.
    // The nil location means UTC.
    // All UTC times are represented with loc==nil, never loc==&utcLoc.
    loc *Location
}

但是,您可以使用指针来执行此操作,因此如果满足您的需要,*time.Time 是可能的。但当然,这是不鼓励的,因为 atomic.LoadPointeratomic.StorePointer 使用 unsafe 包来实现它们的魔力.

一个更好的方法(如果它对您有用)就是使用互斥体来保护您的值。有很多方法可以做到这一点,但举一个最简单的例子:

type MyTime struct {
    t  time.Time
    mu sync.RWMutex
}

func (t *MyTime) Time() time.Time {
    t.mu.RLock()
    defer t.mu.RUnlock()
    return t.t
}

func (t *MyTime) SetTime(tm time.Time) {
    t.mu.Lock()
    defer t.mu.Unlock()
    t.t = tm
}

关于go - 如何在 Go 中将 time.Time 变量转换为原子变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50423209/

相关文章:

go - 尝试检索个人资料信息时 linkedin 登录返回 404

c++ - 在二维数组上进行比较和交换

c++ - 为什么只能保证std::atomic_flag是无锁的?

c++ - 数组中的多线程写操作

java - 在64位JVM上是双原子的读写吗?

使用 select 的 Golang channel 不会停止

regex - 如何在复杂的golang正则表达式捕获中捕获多个组

go - 为什么 "close"不是保留关键字?

database - NimbusDB - 分布式、非阻塞、原子提交协议(protocol)?

go - Mutex 似乎没有正确锁定