在Linux中使用Golang进行并发编程时,可以利用Go语言提供的轻量级线程(goroutines)和通道(channels)来实现高效的并发处理。以下是一些使用Golang在Linux中进行并发编程的技巧:
go
关键字来启动一个新的goroutine。func printNumbers() {
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}
func main() {
go printNumbers() // 启动一个新的goroutine
// 主goroutine继续执行
fmt.Println("Main function")
}
make(chan Type)
来创建一个通道。func sender(ch chan<- int) {
for i := 1; i <= 5; i++ {
ch <- i // 发送数据到通道
}
close(ch) // 关闭通道
}
func receiver(ch <-chan int) {
for num := range ch {
fmt.Println(num)
}
}
func main() {
ch := make(chan int)
go sender(ch)
receiver(ch)
}
sync.WaitGroup
来等待一组goroutines完成。func worker(id int, wg *sync.WaitGroup) {
defer wg.Done() // 在函数结束时调用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) // 增加WaitGroup的计数
go worker(i, &wg)
}
wg.Wait() // 等待所有goroutines完成
}
select
语句可以让goroutine等待多个通信操作。func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
ch1 <- "one"
}()
go func() {
time.Sleep(2 * time.Second)
ch2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-ch1:
fmt.Println("Received", msg1)
case msg2 := <-ch2:
fmt.Println("Received", msg2)
}
}
}
sync.Mutex
来保护共享资源。var mu sync.Mutex
var count int
func increment() {
mu.Lock()
defer mu.Unlock()
count++
}
func main() {
for i := 0; i < 1000; i++ {
go increment()
}
time.Sleep(time.Second)
fmt.Println(count) // 应该输出1000
}
context
包提供了取消信号和超时控制。func worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("Worker cancelled")
return
default:
fmt.Println("Working...")
time.Sleep(time.Second)
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
go worker(ctx)
<-ctx.Done() // 等待context超时
}
通过这些技巧,你可以在Linux环境中高效地使用Golang进行并发编程。记住,合理使用goroutines和channels,并注意同步和竞态条件,可以编写出高性能且可靠的并发程序。