在Golang中,锁机制主要通过sync包来实现。sync包提供了多种锁类型,如互斥锁(Mutex)、读写锁(RWMutex)等。
下面是一个使用互斥锁实现高性能并发处理的示例:
package mainimport ("fmt""sync""time")type Data struct {value intlock sync.Mutex}func main() {data := Data{}var wg sync.WaitGroupfor i := 0; i < 1000; i++ {wg.Add(1)go func(i int) {defer wg.Done()data.setValue(i)}(i)}wg.Wait()fmt.Println(data.getValue())}func (d *Data) setValue(value int) {d.lock.Lock()defer d.lock.Unlock()time.Sleep(time.Millisecond) // 模拟耗时操作d.value += value}func (d *Data) getValue() int {d.lock.Lock()defer d.lock.Unlock()return d.value}在示例中,Data结构体表示共享数据,其中的lock字段是一个互斥锁对象。setValue方法和getValue方法分别对value字段进行写操作和读操作,使用互斥锁进行保护。
在main函数中,使用WaitGroup来等待所有goroutine完成。每个goroutine调用setValue方法将自己的值累加到Data的value字段上。
通过使用互斥锁,可以确保在并发情况下对共享数据的安全访问。

