Advertisement
Falexom

Untitled

May 14th, 2024
544
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.80 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "sync"
  6. )
  7.  
  8. type ThreadPool interface {
  9.     Start(q *UnboundedBlockingQueue)
  10.     Submit(q *UnboundedBlockingQueue, task func())
  11.     Stop()
  12. }
  13.  
  14. type TP struct {
  15.     threads int
  16.     stopped bool
  17. }
  18.  
  19. type UnboundedBlockingQueue struct {
  20.     mu    sync.Mutex
  21.     queue []func()
  22. }
  23.  
  24. func NewUnboundedBlockingQueue() *UnboundedBlockingQueue {
  25.     return &UnboundedBlockingQueue{
  26.         queue: make([]func(), 0),
  27.     }
  28. }
  29.  
  30. func (q *UnboundedBlockingQueue) Put(item func()) {
  31.     q.mu.Lock()
  32.     defer q.mu.Unlock()
  33.  
  34.     q.queue = append(q.queue, item)
  35. }
  36.  
  37. func (q *UnboundedBlockingQueue) Get() func() {
  38.     q.mu.Lock()
  39.     defer q.mu.Unlock()
  40.  
  41.     if len(q.queue) == 0 {
  42.         return nil
  43.     }
  44.  
  45.     item := q.queue[0]
  46.     q.queue = q.queue[1:]
  47.     return item
  48. }
  49.  
  50. func NewThreadPool(count int) *TP {
  51.     return &TP{
  52.         threads: count,
  53.         stopped: false,
  54.     }
  55. }
  56.  
  57. func (tp *TP) Start(q *UnboundedBlockingQueue) {
  58.     var wg sync.WaitGroup
  59.  
  60.     for i := 0; i < tp.threads; i++ {
  61.         wg.Add(1)
  62.         go func() {
  63.             defer wg.Done()
  64.             for {
  65.                 task := q.Get()
  66.                 if task == nil {
  67.                     break
  68.                 }
  69.                 task()
  70.             }
  71.         }()
  72.     }
  73.     wg.Wait()
  74. }
  75.  
  76. func (tp *TP) Submit(q *UnboundedBlockingQueue, task func()) {
  77.     q.Put(task)
  78. }
  79.  
  80. func (tp *TP) Stop() {
  81.     tp.stopped = true
  82. }
  83.  
  84. func taskPrintHelloWorld() {
  85.     fmt.Println("Hello world!")
  86. }
  87.  
  88. func taskCalcAB() {
  89.     a := 2
  90.     b := 3
  91.     c := a + b
  92.     fmt.Printf("%d + %d = %d\n", a, b, c)
  93. }
  94.  
  95. func taskFizz() {
  96.     fmt.Println("Fizz")
  97. }
  98.  
  99. func taskBuzz() {
  100.     fmt.Println("Buzz")
  101. }
  102.  
  103. func main() {
  104.     tq := NewUnboundedBlockingQueue()
  105.     tp := NewThreadPool(4)
  106.  
  107.     tp.Submit(tq, taskPrintHelloWorld)
  108.     tp.Submit(tq, taskFizz)
  109.     tp.Submit(tq, taskCalcAB)
  110.     tp.Submit(tq, taskBuzz)
  111.     tp.Submit(tq, taskBuzz)
  112.     tp.Submit(tq, taskFizz)
  113.     tp.Submit(tq, taskPrintHelloWorld)
  114.     tp.Start(tq)
  115.     tp.Stop()
  116. }
  117.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement