启动两个线程, 一个输出 1,3,5,7…99, 另一个输出 2,4,6,8…100 最后 STDOUT 中按序输出 1,2,3,4,5…100?

aside section._1OhGeD · · 1386 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

时间:2019.10.30
背景:在一个摸鱼群里看到一道面试题,这里用golang实现练习巩固相关知识。
问题:启动两个线程, 一个输出 1,3,5,7…99, 另一个输出 2,4,6,8…100 最后 STDOUT 中按序输出 1,2,3,4,5…100?
语言:Golang

1.用 sync.Cond 实现

sync.Cond 实现了一个条件变量,在 Locker 的基础上增加了一个消息通知的功能,其内部维护了一个等待队列,队列中存放的是所有等待在这个 sync.Cond 的 Go 程,即保存了一个通知列表。sync.Cond 可以用来唤醒一个或所有因等待条件变量而阻塞的 Go 程,以此来实现多个 Go 程间的同步。sync.Cond 的定义及成员函数如下:

type Cond struct {
    // L is held while observing or changing the condition
    L Locker
    // contains filtered or unexported fields
}

//创建一个带锁的条件变量,Locker 通常是一个 *Mutex 或 *RWMutex
func NewCond(l Locker) *Cond

//唤醒所有因等待条件变量 c 阻塞的 goroutine
func (c *Cond) Broadcast()

//唤醒一个因等待条件变量 c 阻塞的 goroutine
func (c *Cond) Signal()

//自动解锁 c.L 并挂起 goroutine。只有当被 Broadcast 和 Signal 唤醒,Wait 才能返回,返回前会锁定 c.L
func (c *Cond) Wait()

代码实现

package dtest

import (
    "fmt"
    "sync"
    "testing"
)

var (
    wg    = sync.WaitGroup{}
    mu    = &sync.Mutex{}
    cond1 = sync.NewCond(mu)
    cond2 = sync.NewCond(mu)
)

func TestT(t *testing.T) {
    wg.Add(2)
    go thread1()
    go thread2()
    wg.Wait()
    fmt.Println("end")
}

func thread1() {
    for i := 1; i <= 100; i += 2 {
        mu.Lock() //获取锁
        if i != 1 {
            cond1.Wait() //等待通知 挂起线程
        }
        fmt.Println("thread1 ->", i)
        mu.Unlock()
        cond2.Broadcast() //通知
    }
    wg.Done()
}

func thread2() {
    for i := 2; i <= 100; i += 2 {
        mu.Lock()
        cond2.Wait()
        fmt.Println("thread2 ->", i)
        mu.Unlock()
        cond1.Broadcast()
    }
    wg.Done()
}

2.用 Channel 实现

Go Channel 的发送与接收默认是阻塞的。当把数据发送到信道时,程序控制会在发送数据的语句处发生阻塞,直到有其它 Go 协程从信道读取到数据,才会解除阻塞。与此类似,当读取信道的数据时,如果没有其它的协程把数据写入到这个信道,那么读取过程就会一直阻塞着。

package dtest

import (
    "fmt"
    "sync"
    "testing"
)

var (
    wg      = sync.WaitGroup{}
    signal1 = make(chan struct{}, 1)
    signal2 = make(chan struct{}, 1)
)

func TestT(t *testing.T) {
    wg.Add(2)
    go thread1()
    go thread2()
    wg.Wait()
    fmt.Println("end")

}

func thread1() {
    for i := 1; i <= 100; i += 2 {
        if i != 1 {
            <-signal1 //读取数据,没有数据时堵塞
        }
        fmt.Println("thread1 ->", i)
        signal2 <- struct{}{} //发送数据
    }
    wg.Done()
}

func thread2() {
    for i := 2; i <= 100; i += 2 {
        <-signal2
        fmt.Println("thread2 ->", i)
        signal1 <- struct{}{}
    }
    wg.Done()
}

输出:

thread1 -> 1
thread2 -> 2
thread1 -> 3
thread2 -> 4
thread1 -> 5
thread2 -> 6
thread1 -> 7
thread2 -> 8
thread1 -> 9
thread2 -> 10
......
thread1 -> 93
thread2 -> 94
thread1 -> 95
thread2 -> 96
thread1 -> 97
thread2 -> 98
thread1 -> 99
thread2 -> 100


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1386 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传