在Go语言中,实现Linux下的并发编程主要依赖于Go的并发原语,如goroutines和channels。以下是一些基本的步骤和示例代码,帮助你在Linux环境下使用Go语言进行并发编程。
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函数完成
}
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")
}
Go语言的sync
包提供了一些用于同步的原始原语,如Mutex
、WaitGroup
等。
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)
}
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")
}
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语言实现高效的并发编程。