golang互斥锁的两种实现

栏目: Go · 发布时间: 7年前

1. 用Mutex实现

package main

import (
    "fmt"
    "sync"
)

var num int
var mtx sync.Mutex
var wg sync.WaitGroup

func add() {
    mtx.Lock()

    defer mtx.Unlock()
    defer wg.Done()

    num += 1
}

func main() {
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go add()
    }

    wg.Wait()

    fmt.Println("num:", num)
}

2. 使用chan实现

package main

import (
    "fmt"
    "sync"
)

var num int

func add(h chan int, wg *sync.WaitGroup) {
    defer wg.Done()

    h <- 1
    num += 1
    <-h
}
func main() {
    ch := make(chan int, 1)
    wg := &sync.WaitGroup{}

    for i := 0; i < 100; i++ {
        wg.Add(1)
        go add(ch, wg)
    }

    wg.Wait()

    fmt.Println("num:", num)
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Foundation Web Standards

Foundation Web Standards

Jonathan Lane、Steve Smith / Friends of ED / 21st July 2008 / $34.99

Foundation Web Standards explores the process of constructing a web site from start to finish. There is more to the process than just knowing HTML! Designers and developers must follow a proper proces......一起来看看 《Foundation Web Standards》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具