-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworker_pool.go
More file actions
75 lines (62 loc) · 1.31 KB
/
worker_pool.go
File metadata and controls
75 lines (62 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"fmt"
"sync"
"time"
)
// Task definition
type Task interface {
Process()
}
// Email task definition
type EmailTask struct {
Email string
Subject string
MessageBody string
}
// Way to process the Email task
func (t *EmailTask) Process() {
fmt.Printf("Sending email to %s\n", t.Email)
// Simulate a time consuming process
time.Sleep(2 * time.Second)
}
// Image processing task
type ImageProcessingTask struct {
ImageUrl string
}
// Way to process the Image
func (t *ImageProcessingTask) Process() {
fmt.Printf("Processing the image %s\n", t.ImageUrl)
// Simulate a time consuming process
time.Sleep(5 * time.Second)
}
// Worker pool definition
type WorkerPool struct {
Tasks []Task
concurrency int
tasksChan chan Task
wg sync.WaitGroup
}
// Functions to execute the worker pool
func (wp *WorkerPool) worker() {
for task := range wp.tasksChan {
task.Process()
wp.wg.Done()
}
}
func (wp *WorkerPool) Run() {
// Initialize the tasks channel
wp.tasksChan = make(chan Task, len(wp.Tasks))
// Start workers
for i := 0; i < wp.concurrency; i++ {
go wp.worker()
}
// Send tasks to the tasks channel
wp.wg.Add(len(wp.Tasks))
for _, task := range wp.Tasks {
wp.tasksChan <- task
}
close(wp.tasksChan)
// Wait for all tasks to finish
wp.wg.Wait()
}