> For the complete documentation index, see [llms.txt](https://minilabmemo.gitbook.io/golang-memo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://minilabmemo.gitbook.io/golang-memo/basic/goroutine/hu-chi-suo.md).

# 互斥鎖

### 互斥鎖

互斥鎖: 傳統的併發會使用鎖來確保區域內只會有一個線程來存取

```
sync.Mutex
mutex.Lock
…. //只有擁有互斥鎖的goroutine 可以執行
mutex.UnLock
```

#### 使用鎖的注意事項:

* Lock/Unlock 需要成對出現，鎖了一次又鎖一次 or 忘了解鎖
* 盡量減少鎖的持有時間
* 可使用defer來正確解鎖

```
mu.Lock()
defer mu.Unlock()  // defer 在函數返回前會執行
….//過程中發生錯誤才不會沒有解鎖
```

**\*如果發生deadlock，有時不會發生警告，而是程式就像是卡住一樣。**

```
fatal error: all goroutines are asleep - deadlock
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://minilabmemo.gitbook.io/golang-memo/basic/goroutine/hu-chi-suo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
