gpt4 book ai didi

objective-c - 如何使用[performSelector : onThread: withObject: waitUntilDone:]?

转载 作者:搜寻专家 更新时间:2023-10-30 20:25:00 25 4
gpt4 key购买 nike

我尝试子类化 NSThread 以便使用一些数据来操作线程。根据文档,我想在 python 中模拟 join() :

join(): Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates

所以我认为使用 performSelector: onThread: withObject: waitUntilDone:YES 会很好,但它不起作用。它什么都不做,也不会退出,永远运行下去。

这是我的代码:

@interface MyClass : NSThread
@property (strong, nonatomic) NSMutableArray *msgQueue;
@property (assign, nonatomic) BOOL stop;
@end

@implementation MyClass

-(id)init
{
self = [super init];
if (self) {
self.msgQueue = [NSMutableArray array];
self.stop = NO;
[self start];
return self;
}
return nil;
}

-(void)myRun
{
while (!self.stop) {
NSLock *arrayLock = [[NSLock alloc] init];
[arrayLock lock];
NSArray *message = [self.msgQueue firstObject];
[self.msgQueue removeObjectAtIndex:0];
[arrayLock unlock];
NSLog(@"%@", message);
if ([message[0] isEqualToString:@"terminate"]) {
self.stop = YES;
}
}
}

-(void)join
{
[self performSelector:@selector(myRun) onThread:self withObject:nil waitUntilDone:YES];
}

@end

int main(int argc, const char * argv[])
{

@autoreleasepool {
MyClass *a = [[MyClass alloc] init];
[a.msgQueue addObject:@[@"terminate",@"hello world"]];
//[a myRun]; // this line works so the myRun method should be good,
[a join]; // but I want this line work, and I have no idea what the problem is.
}
return 0;
}

最佳答案

来自苹果关于 performSelector:onThread:withObject:waitUntilDone: 的文档:

This method queues the message on the run loop of the target thread using the default run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the target thread dequeues the message (assuming it is running in one of the default run loop modes) and invokes the desired method.

您可能从未在线程上启动运行循环,因此它永远不会执行您的 myRun 方法,因为它没有可执行的运行循环。

至于 Merlevede 的回答,myRun 没有在与 join 相同的线程上排队。 join 在您的主线程上被调用,而您正试图在您的辅助线程上排队 myRun。所以他的理论是不正确的。同样来自 Apple 关于等待参数的文档:

If the current thread and target thread are the same, and you specify YES for this parameter, the selector is performed immediately on the current thread. If you specify NO, this method queues the message on the thread’s run loop and returns, just like it does for other threads. The current thread must then dequeue and process the message when it has an opportunity to do so.

所以即使是在同一个线程,也不会卡在等待中,直接执行就好像你直接调用了方法一样,而不是使用performSelector:第一名。

关于objective-c - 如何使用[performSelector : onThread: withObject: waitUntilDone:]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22023184/

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