我们什么时候应该使用 goroutine?我认为我们应该在磁盘或网络 I/O 时使用它以避免阻塞程序。
例如,当我们想从Redis中获取一些数据时。
如果没有 goroutine,我们会这样做:
res, _ := redis.Get(context.Background(), "test_key").Result()
Run Code Online (Sandbox Code Playgroud)
使用 goroutine,我们可以这样做:
ch := make(chan string)
go func() {
res, _ := redis.Get(context.Background(), "test_key").Result()
ch <- res
}()
res := <-ch
Run Code Online (Sandbox Code Playgroud)
我觉得这个方法比上面的好。我理解正确吗?
我知道,如果goroutine B是从某个goroutine A开始的,如果goroutine A结束,那么无论goroutine B走多远,它都会被强制结束。
\nfunc main() {\n go simulateGinAPI()\n fmt.Println("finish...")\n}\n\nfunc simulateGinAPI() {\n fmt.Println("ginAPI....")\n go backgroundProcess()\n}\n\n\nfunc backgroundProcess() {\n fmt.Println("calculating...")\n fmt.Println(calculate(45))\n}\n\nfunc calculate(x int) int {\n if x < 2 {\n return x\n }\n return calculate(x-1) + calculate(x-2)\n}\nRun Code Online (Sandbox Code Playgroud)\n输出
\nfunc main() {\n go simulateGinAPI()\n fmt.Println("finish...")\n}\n\nfunc simulateGinAPI() {\n fmt.Println("ginAPI....")\n go backgroundProcess()\n}\n\n\nfunc backgroundProcess() {\n fmt.Println("calculating...")\n fmt.Println(calculate(45))\n}\n\nfunc calculate(x int) int {\n if x < 2 {\n return x\n }\n return calculate(x-1) + calculate(x-2)\n}\nRun Code Online (Sandbox Code Playgroud)\n正如输出日志所示。斐波那契和的结果不会被注销,而是仅注销“完成”。
\n然而,正如下面的代码所示,如果我们从 Gin 的句柄开始 goroutine,即使发送了响应,计算斐波那契和结果的 goroutine …
我试图以这种方式并行读取多个文件,以便每个读取文件的 go 例程将其数据写入该通道,然后有一个 go 例程监听该通道并将数据添加到映射中。这是我的玩法。
下面是剧中的例子:
package main
import (
"fmt"
"sync"
)
func main() {
var myFiles = []string{"file1", "file2", "file3"}
var myMap = make(map[string][]byte)
dataChan := make(chan fileData, len(myFiles))
wg := sync.WaitGroup{}
defer close(dataChan)
// we create a wait group of N
wg.Add(len(myFiles))
for _, file := range myFiles {
// we create N go-routines, one per file, each one will return a struct containing their filename and bytes from
// the file via the dataChan …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用缓冲通道在 Golang 中创建生产者-消费者消息队列系统。这是我的实现。
package main
import "fmt"
type MessageQueue struct {
storage chan int
count int
}
var done = make(chan bool)
func NewMessageQueue(count int) *MessageQueue {
ret := &MessageQueue{
count: count,
storage: make(chan int, count),
}
return ret
}
func (m *MessageQueue) Produce() {
for i := 0; i < m.count; i++ {
m.storage <- i + 1
}
done <- true
}
func (m *MessageQueue) Consume(f func(int) int) {
for each := range m.storage {
fmt.Printf("%d ", f(each)) …Run Code Online (Sandbox Code Playgroud) 在下面的代码中,对的调用io.Copy永远不会返回;它只是无限期地阻塞,导致死锁。io.Pipe仅当使用 来连接read io.Reader时,才会出现此行为os.Stdout io.Writer。但是,我需要使用管道,因为在我的完整代码中,我使用io.MultiWriterwith io.Pipes 将一个函数连接io.Reader到多个需要io.Reader.
func main() {
read := strings.NewReader("abcdefghij")
pipeReader, pipeWriter := io.Pipe()
var wg sync.WaitGroup
wg.Add(1)
go func() {
println("Start copy")
_, err := io.Copy(os.Stdout, pipeReader)
if err != nil {
println(err.Error())
}
println("End copy")
wg.Done()
}()
_, err := io.Copy(pipeWriter, read)
if err != nil {
println(err.Error())
}
wg.Wait()
}
Run Code Online (Sandbox Code Playgroud)
输出:
Start copy
abcdefghij
fatal error: all goroutines are asleep …Run Code Online (Sandbox Code Playgroud) 我是Golang的初学者,我想在Go中实现类似于Java中的映射诊断上下文(MDC)的东西,这是通过线程本地存储来实现的。但是,我发现很难在网上找到有关 Go 中全局线程本地存储的信息。
我有几个问题:
是否可以为Go中的每个goroutine创建一种全局线程本地存储来存储数据和上下文?
尝试实现全局线程局部存储是否被认为是 Go 中的反模式?
是否建议通过在 Go 中实现全局线程本地存储来替代传递上下文的方式?
假设您的选择是,您更喜欢使用传递上下文的方法,还是尝试实现线程本地存储来保存和管理上下文?
我找到了一些对此的参考,但我无法得出结论来决定是否实施它。
我正在尝试实现这里建议的观察者模式; Go语言中的观察者模式
(上面列出的代码不编译且不完整).这里是一个完整的代码编译,但我得到死锁错误.
package main
import (
"fmt"
)
type Publisher struct{
listeners []chan int
}
type Subscriber struct{
Channel chan int
Name string
}
func (p *Publisher) Sub(c chan int){
p.listeners = append(p.listeners, c)
}
func (p *Publisher) Pub(m int, quit chan int){
for _, c := range p.listeners{
c <- m
}
quit <- 0
}
func (s *Subscriber) ListenOnChannel(){
data := <-s.Channel
fmt.Printf("Name: %v; Data: %v\n", s.Name, data)
}
func main() {
quit := make(chan int)
p …Run Code Online (Sandbox Code Playgroud) 我遇到了goroutines的问题.为什么这段代码在~125ms内执行(注意顺序执行):
package main
import (
"os/exec"
"time"
"fmt"
)
func main() {
cmd := exec.Command("lessc", "--yui-compress", "test.less")
n := 2000
start := time.Now()
for i := 0; i < n; i++ {
cmd.Run()
}
finish := time.Now()
fmt.Printf("Program took %v to run\n", finish.Sub(start))
}
Run Code Online (Sandbox Code Playgroud)
当此代码大约需要20秒时(使用goroutines并发执行):
package main
import (
"os/exec"
"time"
"fmt"
)
func main() {
cmd := exec.Command("lessc", "--yui-compress", "test.less")
ch := make(chan bool)
n := 2000
start := time.Now()
for i := 0; i < n; i++ { …Run Code Online (Sandbox Code Playgroud) 我一直在玩A Tour of Go中的以下代码,但是当我应用一些小的改动时,我不明白发生了什么.原始代码是这样的
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
Run Code Online (Sandbox Code Playgroud)
它产生了这个
world
hello
hello
world
world
hello
hello
world
world
hello
Run Code Online (Sandbox Code Playgroud)
哪个好:五次你好,五次世界.我打电话的时候开始变得奇怪
say("world")
go say("hello")
Run Code Online (Sandbox Code Playgroud)
现在输出就是
world
world
world
world
world
Run Code Online (Sandbox Code Playgroud)
不管你好吗?它有两个goroutines甚至更奇怪
go say("world")
go say("hello")
Run Code Online (Sandbox Code Playgroud)
现在根本没有输出.当我换i < 5到i < 2并打电话
go say("world")
say("hello")
Run Code Online (Sandbox Code Playgroud)
我明白了
world
hello …Run Code Online (Sandbox Code Playgroud) 假设我们有一个这样的方法:
func method(intr MyInterface) {
go intr.exec()
}
Run Code Online (Sandbox Code Playgroud)
在单元测试中method,我们要断言inter.exec已被调用过一次,只有一次。因此我们可以在测试中使用另一个模拟结构对其进行模拟,这将为我们提供检查其是否已被调用的功能:
type mockInterface struct{
CallCount int
}
func (m *mockInterface) exec() {
m.CallCount += 1
}
Run Code Online (Sandbox Code Playgroud)
在单元测试中:
func TestMethod(t *testing.T) {
var mock mockInterface{}
method(mock)
if mock.CallCount != 1 {
t.Errorf("Expected exec to be called only once but it ran %d times", mock.CallCount)
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,由于intr.exec是通过go关键字调用的,因此无法确定在测试中到达断言时是否已调用它。
在参数上添加一个通道intr.exec可能会解决此问题:我们可以在测试中等待从该对象接收任何对象,并且在从该对象接收到对象之后,我们可以继续断言它正在被调用。此通道将在生产(非测试)代码中完全不使用。这可以工作,但是会给非测试代码增加不必要的复杂性,并且可能会使大型代码库变得难以理解。
在断言之前在测试中添加相对较小的睡眠可以使我们确信在睡眠完成之前将调用goroutine:
func TestMethod(t *testing.T) {
var mock mockInterface{}
method(mock)
time.sleep(100 * time.Millisecond)
if …Run Code Online (Sandbox Code Playgroud)