Golang concurrent programming: using Go WaitGroup to implement task scheduler

王林
Release: 2023-09-27 14:51:39
Original
1233 people have browsed it

Golang并发编程:使用Go WaitGroup实现任务调度器

Golang concurrent programming: using Go WaitGroup to implement task scheduler

  1. Introduction
    In Golang, implementing concurrent programming can greatly improve the performance and performance of the program. efficiency. The task scheduler is a very important part of concurrent programming. It can be used to schedule the execution sequence of concurrent tasks and the completion of synchronized tasks. This article will introduce how to use WaitGroup in Golang to implement a simple task scheduler and give specific code examples.
  2. Introduction to WaitGroup
    WaitGroup is an important type in the Golang package sync, which provides synchronization and waiting functions for concurrent tasks. WaitGroup has three main methods: Add, Done and Wait.
  • Add(n int): Add n concurrent tasks to WaitGroup.
  • Done(): Marks a task as completed.
  • Wait(): Wait for all tasks to be completed and block the current goroutine.

WaitGroup maintains a counter internally to record the number of unfinished tasks. When the Add method is called, the counter is incremented by the specified value; when the Done method is called, the counter is decremented by 1; when the Wait method is called, if the counter is greater than 0, the current goroutine will be blocked until the counter returns to zero.

  1. Task Scheduler Implementation
    The following is a sample code that uses WaitGroup to implement a task scheduler:
package main

import (
    "fmt"
    "sync"
    "time"
)

func worker(id int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Printf("Worker %d starting
", id)
    time.Sleep(time.Second)
    fmt.Printf("Worker %d done
", id)
}

func main() {
    var wg sync.WaitGroup
    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go worker(i, &wg)
    }
    wg.Wait()
    fmt.Println("All workers done")
}
Copy after login

In this example, we use a for loop to start 5 worker goroutines, and add the number of tasks to the WaitGroup by calling wg.Add(1). In the worker function, use the defer keyword to ensure that wg.Done() is called before the function returns to decrement the counter value. Finally, use wg.Wait() to wait for all tasks to complete.

  1. Run results
    Run this sample code, you will see the following output:
Worker 1 starting
Worker 2 starting
Worker 3 starting
Worker 4 starting
Worker 5 starting
Worker 3 done
Worker 1 done
Worker 2 done
Worker 5 done
Worker 4 done
All workers done
Copy after login

You can see that all worker goroutines are executed concurrently, However, the order of output is not necessarily in the startup order, because goroutine scheduling is performed by the Go runtime.

  1. Summary
    Using WaitGroup can easily implement the scheduling and synchronization of concurrent tasks. Synchronization and sequence control of tasks can be achieved by calling the Add method to add the number of tasks, calling the Done method to mark task completion, and calling the Wait method to wait for task completion. In practical applications, the task scheduler can be used to handle concurrent tasks, limit the number of concurrencies, and other scenarios, helping us make better use of Golang's concurrency capabilities.

Through the introduction and sample code of this article, I believe you have a deeper understanding of how to use Golang's WaitGroup to implement a task scheduler. I hope this article will help you learn and use concurrent programming in Golang!

The above is the detailed content of Golang concurrent programming: using Go WaitGroup to implement task scheduler. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!