gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:06:32 27 4
gpt4 key购买 nike

这是我的代码:

@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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com