官术网_书友最值得收藏!

The sync package

The last topic we will cover in this chapter is the sync package. The sync package is what you will use when you absolutely need to create a lock-in Go. Even though we mentioned that Go prefers the use of channels to communicate data between goroutines, there are cases where a lock or a mutual exclusion object (mutexis unavoidable. An example of a scenario where locks are utilized in Go's standard package is the http package, where a lock is used to protect the set of listeners to a particular http server object. This set of listeners can be accessed from numerous goroutines so that they get protected by a mutex.

The word mutex, in the world of computer programming, refers to an object that allows multiple threads to access the same resource (such as shared memory). Mutex is so named because it allows only one thread to access data at one time. 

The workflow of a mutex in a piece of software typically works as follows:

  1. A thread acquires the mutex
  2. No other threads can acquire the mutex as long as one thread has it
  3. The thread that acquired the mutex can access some resources without any disturbance from the other threads
  4. When its tasks are done, the thread that acquired the mutex releases the mutex so that other threads can compete for it again

In Go, you make use of goroutines and not full threads. So, when you use mutexes in Go, they will manage the resource access between goroutines.

Let's take a look at the simple mutex, read-write mutex and wait groups in the next sections.

主站蜘蛛池模板: 华亭县| 武冈市| 新平| 朝阳县| 炎陵县| 日土县| 麻栗坡县| 五峰| 和田县| 慈溪市| 淄博市| 阳新县| 兖州市| 莫力| 仙居县| 诸暨市| 磐石市| 塘沽区| 林甸县| 江门市| 信丰县| 康平县| 江津市| 南丹县| 余江县| 张家口市| 繁峙县| 宁陕县| 广宁县| 锡林浩特市| 平顺县| 洛川县| 乐清市| 阿坝县| 漳浦县| 呼图壁县| 西峡县| 桃江县| 西峡县| 祁连县| 诸暨市|