致命错误:所有goroutine都在睡着-死锁!打印结果时

时间:2019-07-24 05:56:21

标签: go

为什么下面的打印结果不起作用?

std::unique_ptr<ASTConsumer> CreateASTConsumer(
    CompilerInstance& compiler, StringRef inFile) override {

    std::unique_ptr<ASTConsumer> consumer1 =
        std::make_unique<MyConsumer1>(compiler);

    std::unique_ptr<ASTConsumer> consumer2 =
        std::make_unique<MyConsumer2>(compiler);

    std::vector<std::unique_ptr<ASTConsumer>> consumers;
    consumers.emplace_back(std::move(consumer1));
    consumers.emplace_back(std::move(consumer2));
    return std::make_unique<MultiplexConsumer>(std::move(consumers));
}

这确实有效

    for o := range out {
        fmt.Println(o)
    }

这不起作用

    for j := 1; j <= 10; j++ {
        fmt.Println(<-out)
    }

有错误

package main

import (
    "fmt"
)

func main() {
    out := make(chan int, 2)
    in := make(chan int, 2)
    for i := 1; i <= 10; i++ {
        go multiplyByTwo(in, out)
        in <- i
    }
    for o := range out {
        fmt.Println(o)
    }
}

func multiplyByTwo(in <-chan int, out chan<- int) {
    num := <-in
    fmt.Printf("Initializing goroutine...%v\n", num)
    result := num * 2
    out <- result
}

这确实有效

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /golang-demo/concurrency_channel_inout/concurrency_channel_inout.go:14 +0x149
exit status 2
Process exiting with code: 1

0 个答案:

没有答案