ios - 有什么方法可以使 dispatch_queue_t 在单线程中工作?

标签 ios grand-central-dispatch nsoperationqueue nsthread

这是我的代码:

@interface MyObject ()
@property(nonatomic) dispatch_queue_t queue;
@end

@implementation MyObject {
    NSThread *_check;
}

- (id)init {
    self = [super init];
    if (self) {
        _queue = dispatch_queue_create("com.Thread.queue", NULL);
        dispatch_async(_queue, ^{
            _check = [NSThread currentThread]; //for ex. thread number = 3
            //some code here...
        });
    }

    return self;
}

- (void)someMethod:(MyObjClass *)obj {
    dispatch_async(_queue, ^{
        //need th
        if (_check != [NSThread currentThread]) { // it is sometimes number 3, but sometimes it changes
            NSLog(@"Thread changed.");
        }
        [obj doSmth]; //got crash if currentThread != _check         
    });
}

@end

我需要确保所有 MyObjClass 的方法都在同一个线程中执行。但是这个代码改变线程是它自己的意志,但有时它在单线程中工作。有什么方法可以强制它一直使用同一个线程?

最佳答案

一句话,没有。除了主队列,GCD 没有任何线程关联的概念。如果你真的需要线程关联,GCD 并不是真正合适的工具。如果您喜欢这个成语,并且想要根据您的需要“调整”某些内容,您可以这样做:

@implementation AppDelegate
{
    NSThread* thread;
}

void dispatch_thread_async(NSThread* thread, dispatch_block_t block)
{
    if ([NSThread currentThread] == thread)
    {
        block();
    }
    else
    {
        block = [block copy];
        [(id)block performSelector: @selector(invoke) onThread: thread withObject: nil waitUntilDone: NO];
    }
}

void dispatch_thread_sync(NSThread* thread, dispatch_block_t block)
{
    if ([NSThread currentThread] == thread)
    {
        block();
    }
    else
    {
        [(id)block performSelector: @selector(invoke) onThread: thread withObject: nil waitUntilDone: YES];
    }
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    thread = [[NSThread alloc] initWithTarget: self selector:@selector(threadMain) object:nil];
    [thread start];

    dispatch_thread_async(thread, ^{
        NSLog(@"Async Thread: %@", [NSThread currentThread]);
    });

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_thread_sync(thread, ^{
            NSLog(@"Sync Thread: %@", [NSThread currentThread]);
        });
    });
}

- (void)threadMain
{
    // You need the NSPort here because a runloop with no sources or ports registered with it
    // will simply exit immediately instead of running forever.
    NSPort* keepAlive = [NSPort port];
    NSRunLoop* rl = [NSRunLoop currentRunLoop];
    [keepAlive scheduleInRunLoop: rl forMode: NSRunLoopCommonModes];
    [rl run];
}

@end

关于ios - 有什么方法可以使 dispatch_queue_t 在单线程中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26819074/

相关文章:

ios - 如何将数据传递给其他iOS应用程序?

ios - 如何使用 CoreAnimation 组合模型将 UIView 层次结构渲染到 CGContext 中

ios - 使用正则表达式从用户代理检测 iOS 版本号

multithreading - 从后台队列调用时,核心数据 NSManagedObjectContext 保存永远不会返回

ios - NSOperation 中的 ASINetworkQueue 错误保存核心数据

iphone - NSOperation mainQueue 问题

ios - 供应配置文件与包标识符不匹配

swift - 运行异步调用时在 MainQueue 上更新什么

swift - 有没有办法取消 DispatchQueue concurrentPerform 操作?

ios - 等待多个 block 完成