草庐IT

Goroutines 和依赖函数

coder 2023-07-01 原文

我在 GO 上玩得很开心,并且对我想要实现的目标非常好奇。我这里有一个包,它只是从 Reddit 上获取一个特殊的提要。当我收到父 JSON 文件时,我想检索子数据。如果您看到下面的代码,我将启动一系列 goroutine,然后将其阻塞,等待它们完成使用 sync 包。我想要的是一旦第一个系列的 goroutines 使用以前的结果完成第二个系列的 goroutines。有一些是我在想的,比如 for 循环和 switch 语句。但是最好和最有效的方法是什么

func (m redditMatcher) retrieve(dataPoint *collect.DataPoint) (*redditCommentsDocument, error) {
    if dataPoint.URI == "" {
        return nil, errors.New("No datapoint uri provided")
    }

    // Get options data -> returns empty struct
    // if no options are present
    options := m.options(dataPoint.Options)
    if len(options.subreddit) <= 0 {
        return nil, fmt.Errorf("Matcher fail: Reddit - Subreddit option manditory\n")
    }

    // Create an buffered channel to receive match results to display.
    results := make(chan *redditCommentsDocument, len(options.subreddit))

    // Generte requests for each subreddit produced using
    // goroutines concurency model
    for _, s := range options.subreddit {
        // Set the number of goroutines we need to wait for while
        // they process the individual subreddit.
        waitGroup.Add(1)
        go retrieveComment(s.(string), dataPoint.URI, results)
    }

    // Launch a goroutine to monitor when all the work is done.
    waitGroup.Wait()

    // HERE I WOULD TO CALL ANOTHER SERIES OFF GOROUTINES
    for commentFeed := range results {
        // HERE I WOULD LIKE TO CALL GO ROUTINES USING THE RESULTS
        // PROVIDED FROM THE PREVIOUS FUNCTIONS
        waitGroup.Add(1)
        log.Printf("%s\n\n", commentFeed.Kind)
    }

    waitGroup.Wait()
    close(results)

    return nil, nil
}

最佳答案

如果你想等待所有第一个系列完成,那么你可以传递一个指向你的 WaitGroup 的指针,在调用所有第一个系列函数(将调用 Done() 在 waitgroup 上),然后开始第二个系列。这是执行此操作的可运行注释代码示例:

package main

import(
    "fmt"
    "sync"
    "time"
)

func first(wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("Starting a first")
    // do some stuff... here's a sleep to make some time pass
    time.Sleep(250 * time.Millisecond)
    fmt.Println("Done with a first")
}

func second(wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("Starting a second")
    // do some followup stuff
    time.Sleep(50 * time.Millisecond)
    fmt.Println("Done with a second")
}

func main() {
    wg := new(sync.WaitGroup) // you'll need a pointer to avoid a copy when passing as parameter to goroutine function

    // let's start 5 firsts and then wait for them to finish
    wg.Add(5)
    go first(wg)
    go first(wg)
    go first(wg)
    go first(wg)
    go first(wg)
    wg.Wait()

    // now that we're done with all the firsts, let's do the seconds
    // how about two of these
    wg.Add(2)
    go second(wg)
    go second(wg)
    wg.Wait()

    fmt.Println("All done")
}

输出:

Starting a first
Starting a first
Starting a first
Starting a first
Starting a first
Done with a first
Done with a first
Done with a first
Done with a first
Done with a first
Starting a second
Starting a second
Done with a second
Done with a second
All done

但是如果您希望“第二个”在“第一个”完成后立即开始,只需让第二个在第一个运行时在 channel 上执行阻塞接收操作符:

package main

import(
    "fmt"
    "math/rand"
    "sync"
    "time"
)

func first(res chan int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("Starting a first")
    // do some stuff... here's a sleep to make some time pass
    time.Sleep(250 * time.Millisecond)
    fmt.Println("Done with a first")
    res <- rand.Int() // this will block until a second is ready
}

func second(res chan int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println("Wait for a value from first")
    val := <-res // this will block until a first is ready
    fmt.Printf("Starting a second with val %d\n", val)
    // do some followup stuff
    time.Sleep(50 * time.Millisecond)
    fmt.Println("Done with a second")
}

func main() {
    wg := new(sync.WaitGroup) // you'll need a pointer to avoid a copy when passing as parameter to goroutine function
    ch := make(chan int)

    // lets run first twice, and second once for each first result, for a total of four workers:
    wg.Add(4)
    go first(ch, wg)
    go first(ch, wg)
    // don't wait before starting the seconds
    go second(ch, wg)
    go second(ch, wg)
    wg.Wait()

    fmt.Println("All done")
}

哪些输出:

Wait for a value from first
Starting a first
Starting a first
Wait for a value from first
Done with a first
Starting a second with val 5577006791947779410
Done with a first
Starting a second with val 8674665223082153551
Done with a second
Done with a second
All done

关于Goroutines 和依赖函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48843267/

有关Goroutines 和依赖函数的更多相关文章

  1. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  2. ruby-on-rails - 在 ruby​​ .gemspec 文件中,如何指定依赖项的多个版本? - 2

    我正在尝试修改当前依赖于定义为activeresource的gem:s.add_dependency"activeresource","~>3.0"为了让gem与Rails4一起工作,我需要扩展依赖关系以与activeresource的版本3或4一起工作。我不想简单地添加以下内容,因为它可能会在以后引起问题:s.add_dependency"activeresource",">=3.0"有没有办法指定可接受版本的列表?~>3.0还是~>4.0? 最佳答案 根据thedocumentation,如果你想要3到4之间的所有版本,你可以这

  3. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  4. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  5. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  6. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  7. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  8. ruby-on-rails - 将字符串转换为 ruby​​-on-rails 中的函数 - 2

    我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。

  9. ruby - 有什么方法可以告诉 sidekiq 一项工作依赖于另一项工作 - 2

    有什么方法可以告诉sidekiq一项工作依赖于另一项工作,并且在后者完成之前无法开始? 最佳答案 仅使用Sidekiq;答案是否定的。正如DickieBoy所建议的那样,您应该能够在依赖作业完成时将其启动。像这样。#app/workers/hard_worker.rbclassHardWorkerincludeSidekiq::Workerdefperform()puts'Doinghardwork'LazyWorker.perform_async()endend#app/workers/lazy_worker.rbclassLaz

  10. ruby - 在 ruby​​ 中使用 .try 函数和 .map 函数 - 2

    我需要从json记录中获取一些值并像下面这样提取curr_json_doc['title']['genre'].map{|s|s['name']}.join(',')但对于某些记录,curr_json_doc['title']['genre']可以为空。所以我想对map和join()使用try函数。我试过如下curr_json_doc['title']['genre'].try(:map,{|s|s['name']}).try(:join,(','))但是没用。 最佳答案 你没有正确传递block。block被传递给参数括号外的方法

随机推荐