作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
这是我的代码:
@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/
我是一名优秀的程序员,十分优秀!