Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9baf068

Browse files
Update goroutine.md
1 parent 35d429f commit 9baf068

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎Multi-Thread/goroutine.md‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,3 +128,60 @@ func consumer(i int, ch chan int) {
128128
}
129129
```
130130

131+
132+
133+
## 手写协程池
134+
135+
```go
136+
package main
137+
138+
import (
139+
"fmt"
140+
"time"
141+
)
142+
143+
type Task struct {
144+
f func()
145+
}
146+
147+
func (t *Task) Execute() {
148+
t.f()
149+
}
150+
151+
type Pool struct {
152+
tasks chan *Task
153+
entry chan *Task
154+
nums int
155+
}
156+
157+
func (p *Pool) Work(id int) {
158+
for task := range p.tasks {
159+
task.Execute()
160+
fmt.Println("excute id: ", id)
161+
time.Sleep(2 * time.Second)
162+
}
163+
}
164+
165+
func (p *Pool) Run() {
166+
for i := 1; i <= p.nums; i++ {
167+
go p.Work(i)
168+
}
169+
for task := range p.entry {
170+
p.tasks <- task
171+
}
172+
}
173+
174+
func main() {
175+
task := &Task{f: func() {
176+
fmt.Println("Execute!", time.Now())
177+
}}
178+
p := &Pool{nums: 3, entry: make(chan *Task), tasks: make(chan *Task)}
179+
go func() {
180+
for {
181+
p.entry <- task
182+
}
183+
}()
184+
p.Run()
185+
}
186+
```
187+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /