-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcircular4.go
65 lines (49 loc) · 1.3 KB
/
circular4.go
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
package main
import (
"fmt"
"sync"
"time"
)
const (
QueueCount = 10000 // Number of circular queues
QueueSize = 10 // Size of each circular queue
ConsumerCount = 10000 // Number of consumers
DataCount = 10000 // Total data items to produce
)
func main() {
start := time.Now()
var wg sync.WaitGroup
queues := make([]chan int, QueueCount)
for i := 0; i < QueueCount; i++ {
queues[i] = make(chan int, QueueSize)
wg.Add(1)
go producer(queues[i], &wg, i)
}
// Create and manage consumers
for i := 0; i < ConsumerCount; i++ {
wg.Add(1)
go consumer(queues[i%QueueCount], &wg, start, DataCount/ConsumerCount)
}
// Wait for all producers and consumers to finish
wg.Wait()
end := time.Now()
timeTaken := end.Sub(start)
fmt.Printf("Total execution time : %s\n", timeTaken)
}
func producer(queue chan<- int, wg *sync.WaitGroup, id int) {
defer wg.Done()
startId := id * (DataCount / QueueCount)
endId := (id + 1) * (DataCount / QueueCount)
for i := startId; i < endId; i++ {
queue <- i
fmt.Printf("Producer %d: Produced: %d\n", id, i)
}
}
func consumer(queue <-chan int, wg *sync.WaitGroup, start time.Time, itemCount int) {
defer wg.Done()
for i := 0; i < itemCount; i++ {
data := <-queue
fmt.Printf("Consumed: %d,", data)
}
}
// Total execution time : 278.428875ms