- Hands-On Full Stack Development with Go
- Mina Andrawos
- 280字
- 2021-07-02 12:33:34
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 (mutex) is 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:
- A thread acquires the mutex
- No other threads can acquire the mutex as long as one thread has it
- The thread that acquired the mutex can access some resources without any disturbance from the other threads
- 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.
- 計算機網絡
- Getting Started with React
- Android項目開發入門教程
- Java EE框架整合開發入門到實戰:Spring+Spring MVC+MyBatis(微課版)
- 實用防銹油配方與制備200例
- Visual Basic程序設計(第3版):學習指導與練習
- GeoServer Beginner's Guide(Second Edition)
- 快速念咒:MySQL入門指南與進階實戰
- C語言程序設計
- 高級語言程序設計(C語言版):基于計算思維能力培養
- Python+Tableau數據可視化之美
- Illustrator CS6設計與應用任務教程
- Nagios Core Administration Cookbook(Second Edition)
- Android應用開發實戰
- IoT Projects with Bluetooth Low Energy