草庐IT

sql - Go 相当于 GCD 串行调度队列

coder 2024-07-08 原文

是否有与 Apple 的 GCD 串行调度队列等效的 Go?

到目前为止,我只找到了一种解决方案,即函数 channel 。

work := make(chan func()) 

我会有一个函数从这个 channel 接收并调用接收到的函数。这些函数必须按 FIFO 顺序执行。

在 Go 中是否有更好的方法或结构来执行此操作?

这应该不会有什么不同,但我希望将 SQL 查询排队以为此在 FIFO 中运行。

最佳答案

@OneOfOne,很接近但不完全是。

我最终在 Go 中实现了串行调度队列可用 here .

它基本上是一个 go 例程,阻塞在 func() 类型的 channel 上,并运行按顺序传递的函数。

实现:

//Package serialqueue provides a serial queue for functions. 
//Queue items are processed in First In First Out (FIFO) order. 
package serialqueue

//New returns a new serial queue.
//Enqueue items like queueObj <- func() {doWork(data)}
func New() chan func() {
    //create channel of type function
    var queue = make(chan func())

    //spawn go routine to read and run functions in the channel
    go func() {
        for true {
            nextFunction := <-queue
            nextFunction()
        }
    }()

    return queue
}

用法:(演示以正确顺序写入字符串)

//Package serialqueue provides provides tests for github.com/ansonl/serialqueue. 
package serialqueue_test

import (
    "testing"
    "fmt"
    "sync"
    "github.com/ansonl/serialqueue"
    )

func TestQueue(t *testing.T) {
    //Create new serial queue
    queue := serialqueue.New()

    //Number of times to loop
    var loops = 100

    //Queue output will be added here
    var queueOutput string

    //WaitGroup for determining when queue output is finished
    var wg sync.WaitGroup

    //Create function to place in queue
    var printTest = func(i int) {
        queueOutput = fmt.Sprintf("%v%v",queueOutput, i)
        wg.Done()
    }

    //Add functions to queue
    var i int;
    for i=0;i<loops;i++ {
        wg.Add(1)
        t:=i
        queue <- func() {printTest(t)}
    }

    //Generate correct output
    var correctOutput string
    for i=0;i<loops;i++ {
        correctOutput = fmt.Sprintf("%v%v", correctOutput, i)       
    }

    //Wait until all functions in queue are done
    wg.Wait()

    //Compare queue output with correct output
    if queueOutput != correctOutput {
        t.Errorf("Serial Queue produced %v, want %v", queueOutput, correctOutput);
    }
}

希望这对遇到同样问题的人有所帮助!

关于sql - Go 相当于 GCD 串行调度队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34926930/

有关sql - Go 相当于 GCD 串行调度队列的更多相关文章

  1. Python 相当于 Perl/Ruby ||= - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。

  2. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  3. Hive SQL 五大经典面试题 - 2

    目录第1题连续问题分析:解法:第2题分组问题分析:解法:第3题间隔连续问题分析:解法:第4题打折日期交叉问题分析:解法:第5题同时在线问题分析:解法:第1题连续问题如下数据为蚂蚁森林中用户领取的减少碳排放量iddtlowcarbon10012021-12-1212310022021-12-124510012021-12-134310012021-12-134510012021-12-132310022021-12-144510012021-12-1423010022021-12-154510012021-12-1523.......找出连续3天及以上减少碳排放量在100以上的用户分析:遇到这类

  4. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

  5. java - Ruby 相当于 Java 的 Collections.unmodifiableList 和 Collections.unmodifiableMap - 2

    Java的Collections.unmodifiableList和Collections.unmodifiableMap在Ruby标准API中是否有等价物? 最佳答案 使用freeze应用程序接口(interface):Preventsfurthermodificationstoobj.ARuntimeErrorwillberaisedifmodificationisattempted.Thereisnowaytounfreezeafrozenobject.SeealsoObject#frozen?.Thismethodretur

  6. python - Ruby 相当于 Python str[3 :] - 2

    是否有Ruby等效于Python的方法来获取在字符串末尾结束的子字符串,如str[3:]?必须输入字符串的长度并不方便。 最佳答案 传递最后一个元素=-1的范围str[3..-1] 关于python-Ruby相当于Pythonstr[3:],我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/12978768/

  7. ruby - Java 8 相当于 ruby​​ each_with_index - 2

    我想知道,是否有一些流操作可以像ruby​​中的each_with_index那样做。其中each_with_index遍历值以及值的索引。 最佳答案 没有专门用于该目的的流操作。但您可以通过多种方式模仿该功能。索引变量:以下方法适用于顺序流。int[]index={0};stream.forEach(item->System.out.printf("%s%d\n",item,index[0]++));外部迭代:以下方法适用于并行流,只要原始集合支持随机访问。Listtokens=...;IntStream.range(0,toke

  8. sql - 在 Rails Console for PostgreSQL 的表中显示数据 - 2

    我找到了这样的东西:Rails:Howtolistdatabasetables/objectsusingtheRailsconsole?这一行没问题:ActiveRecord::Base.connection.tables并返回所有表但是ActiveRecord::Base.connection.table_structure("users")产生错误:ActiveRecord::Base.connection.table_structure("projects")我认为table_structure不是Postgres方法。如何列出Postgres数据库的Rails控制台中表中的所有

  9. ruby - 防止SQL注入(inject)/好的Ruby方法 - 2

    Ruby中防止SQL注入(inject)的好方法是什么? 最佳答案 直接使用ruby?使用准备好的语句:require'mysql'db=Mysql.new('localhost','user','password','database')statement=db.prepare"SELECT*FROMtableWHEREfield=?"statement.execute'value'statement.fetchstatement.close 关于ruby-防止SQL注入(inject

  10. ruby - setInterval() 相当于 ruby - 2

    在JavaScript中你可以这样做:setInterval(func,delay);我似乎无法在谷歌上找到任何我真正要找的东西。是否有ruby等价物?提前致谢。 最佳答案 你可以做类似的事情:Thread.newdoloopdosleepdelay#yourcodehereendend或者你可以定义一个函数:#@return[Thread]returnloopthreadreferencedefset_interval(delay)Thread.newdoloopdosleepdelayyield#callpassedblocke

随机推荐