使用GCD的FIFO串行队列 [英] FIFO serial queue using GCD

查看:148
本文介绍了使用GCD的FIFO串行队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我工作的公司创建一个(网络)同步阵列.虽然网络部分工作正常,但我陷入了一个问题.

I am trying to create a (network) synchronized array for the company I work for. While the networking part works fine, I have dwelled into an issue.

我的愿望是使用dispatch_create_queue创建一个新队列,在该队列中我将添加两个的块,它们以串行方式运行在主线程上,这意味着首先第一个程序块必须运行,然后第二个程序块必须运行,并且永远不能并行运行.

My wish was to create a new queue using dispatch_create_queue, to which I would add two blocks that are not to run on the main thread, but in a serial manner, meaning that first the first block has to run, then the second, and never in parallel.

我已经阅读了Apple文档,但至少可以这样说令人困惑.

I've read the apple documentation, but it is confusing to say the least.

  • 当我使用dispatch_queue_create创建队列,然后使用dispatch_sync添加块(在定义它们之后)时,我发现该块仍在主线程上执行.

  • When I create my queue using dispatch_queue_create and then add the blocks (after they have been defined) using dispatch_sync, I have found out that the block is still executing on the main thread.

使用dispatch_async时,即在主线程上未执行块时.

When using dispatch_async, thats when the blocks are not executing on the main thread.

当我尝试使用dispatch_sync添加两个块时,它们将永远被阻止.

When I try to add both blocks using dispatch_sync They get blocked forever.

这两个块似乎都只能在调用dispatch_async时运行良好并且脱离主线程.

The only time that both blocks seem to run fine and off the main thread is when calling dispatch_async.

但是我之所以选择GCD和sync方法,是为了给人一种印象,即我正在创建一个新队列(从而创建了一个新线程),并且向该队列添加块只会阻塞一个队列,直到另一个队列被阻塞为止.完成执行.是不是这样,或者创建队列并不能保证代码不会在主线程上运行?

However the reason why I chose GCD and the sync method so that I was under the impression that I was creating a new queue (and thus a new thread) and that adding blocks to that queue would simply block one until the other had finished executing. Is this not the case, or does creating a queue does not guarantee that the code will not run on the main thread ?

推荐答案

这是GCD中的FIFO队列:

This is a FIFO queue in GCD:

dispatch_queue_t serialQueue = dispatch_queue_create("com.blah.queue", DISPATCH_QUEUE_SERIAL);

...
dispatch_async(serialQueue, ^{
    //block1
});

dispatch_async(serialQueue, ^{
    //block2
});

这篇关于使用GCD的FIFO串行队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆