溫馨提示×

Go語言在Linux下的并發編程怎樣實現

小樊
48
2025-06-29 08:41:56
欄目: 編程語言

在Go語言中,實現Linux下的并發編程主要依賴于Go的并發原語,如goroutines和channels。以下是一些基本的步驟和示例代碼,幫助你在Linux環境下使用Go語言進行并發編程。

1. 創建Goroutines

Goroutines是Go語言中的輕量級線程,可以輕松創建和管理。你只需要在函數調用前加上go關鍵字即可啟動一個新的goroutine。

package main

import (
	"fmt"
	"time"
)

func printNumbers() {
	for i := 1; i <= 5; i++ {
		fmt.Printf("Number: %d\n", i)
		time.Sleep(1 * time.Second)
	}
}

func main() {
	go printNumbers() // 啟動一個新的goroutine

	// 主goroutine繼續執行
	fmt.Println("Main goroutine is running")
	time.Sleep(6 * time.Second) // 等待printNumbers函數完成
}

2. 使用Channels進行通信

Channels是Go語言中用于goroutines之間通信和同步的原語。你可以使用make(chan Type)創建一個channel,并使用<-操作符發送和接收數據。

package main

import (
	"fmt"
	"time"
)

func producer(ch chan<- int) {
	for i := 1; i <= 5; i++ {
		ch <- i // 發送數據到channel
		time.Sleep(1 * time.Second)
	}
	close(ch) // 關閉channel
}

func consumer(ch <-chan int, done chan<- bool) {
	for num := range ch { // 從channel接收數據
		fmt.Printf("Received: %d\n", num)
	}
	done <- true // 發送完成信號
}

func main() {
	ch := make(chan int)   // 創建一個用于傳遞整數的channel
	done := make(chan bool) // 創建一個用于通知完成的channel

	go producer(ch)       // 啟動生產者goroutine
	go consumer(ch, done) // 啟動消費者goroutine

	<-done // 等待消費者goroutine完成
	fmt.Println("Main goroutine is done")
}

3. 使用sync包進行同步

Go語言的sync包提供了一些用于同步的原始原語,如Mutex、WaitGroup等。

使用Mutex進行互斥鎖

package main

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

var (
	counter int
	mutex   sync.Mutex
)

func increment() {
	for i := 0; i < 100000; i++ {
		mutex.Lock()
		counter++
		mutex.Unlock()
	}
}

func main() {
	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		defer wg.Done()
		increment()
	}()

	go func() {
		defer wg.Done()
		increment()
	}()

	wg.Wait()
	fmt.Println("Counter:", counter)
}

使用WaitGroup進行等待

package main

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

func worker(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Printf("Worker %d starting\n", id)
	time.Sleep(time.Second)
	fmt.Printf("Worker %d done\n", 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")
}

4. 使用context進行超時和取消

context包提供了用于管理goroutines生命周期的原語,如超時和取消。

package main

import (
	"context"
	"fmt"
	"time"
)

func doSomething(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("Context cancelled or timed out")
			return
		default:
			fmt.Println("Working...")
			time.Sleep(500 * time.Millisecond)
		}
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	go doSomething(ctx)

	<-ctx.Done()
	fmt.Println("Main goroutine is done")
}

通過這些基本的并發原語和模式,你可以在Linux環境下使用Go語言實現高效的并發編程。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女