Go中的单例模式

Jul 12, 2015

Jul 12, 2015

The Go Language growth has been phenomenal in the last few years, and is attracting language converts from all walks of life. There has been a lot articles recently about companies switching from Ruby, and experiencing the new world of Go and it’s parallel and concurrent approach to problems.

Go语言在过去几年中的增长是惊人的,并吸引了来自各行各业的语言转换者。最近有很多关于公司从Ruby转换到Go并体验其并行和并发解决方案的文章。

In the last 10 years, Ruby on Rails has allowed many developers and startups to quickly develop powerful systems, most of the time without needing to worry on how the inner things work, or worry about thread-safety and concurrency. It is very rare for a RoR application to create threads and run things in parallel. The whole hosting infrastructure and framework stack uses a different approach, by parallelizing it via multiple processes. It has only been in the last few years that multithreaded rack servers like Puma has surged in popularity, but even that brought a lot of issues in the beggining with third-party gems and other code that weren’t designed to be thread safe.

在过去的10年中,Ruby on Rails使许多开发人员和初创公司能够快速开发强大的系统,大多数情况下无需担心内部工作原理,也无需担心线程安全和并发性。对于RoR应用程序来说,创建线程并并行运行是非常罕见的。整个托管基础架构和框架堆栈使用了一种不同的方法,通过多个进程进行并行化。直到最近几年,像Puma这样的多线程rack服务器才开始流行起来,但即使如此,它也带来了很多问题,因为第三方gems和其他代码并没有设计成线程安全的。

Now with a lot of new developers embarking into the Go Language boat, we need to carefully look at our code and see how it will behave, it needs to be designed in a thread-safe way.

现在,随着越来越多的新开发人员开始使用Go语言,我们需要仔细检查我们的代码并了解它的行为方式,它需要以线程安全的方式进行设计。

The Common Mistake

常见错误

Recently, I have seen this kind of mistake more and more in github repositories. Singleton implementations that doesn’t have any consideration for thread-safety. Below is the most common example of this mistake.

最近,在GitHub存储库中越来越多地看到这种错误的解决方案。单例实现没有考虑线程安全性。下面是这种错误的最常见示例。

package singleton type singleton struct {
} var instance *singleton func GetInstance() *singleton { if instance == nil { instance = &singleton{} } return instance
}

In the above scenario, multiple go routines could eval...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.125.0. UTC+08:00, 2024-05-04 19:42
浙ICP备14020137号-1 $访客地图$