0

我想在新线程上启动一个守护进程,我的程序在等待来自守护进程的输入时不会锁定,但我需要一种方法让主程序从守护进程获取信息。我已经使用 NSThread 触发了一个新线程,但是我看不到如何将委托与 NSThread 一起使用。

有关更多上下文,我正在为 Quartz Composer 开发一个自定义补丁,该补丁将从网络接收数据。这个想法是第二个线程可以运行守护程序,并且在每一帧上,当守护程序线程接收到新数据时,我会从委托方法设置的 ivar 中获取新数据。在此期间,组合运行与没有中断。

我可以用 NSThread 做到这一点吗?有没有更好的方法我应该看看?

4

2 回答 2

2

您可能还想考虑使用操作队列 (NSOperation) 或调度队列 (GCD) 而不是 NSThread。

如果您还没有,请查看 Apple 的并发编程指南;他们真的推荐基于队列的方法,而不是显式创建线程。

于 2011-11-15T04:09:56.193 回答
1

编辑:如果您希望委托回调在主线程上发生,请使用此模式:[delegate performSelectorOnMainThread:@selector(threadDidSomething:) withObject:self waitUntilDone:NO]

干得好。我相信这是不言自明的,但如果不是,请告诉我。请注意:我只是根据API编写了这段代码,但没有测试过,所以要小心。

@protocol ThreadLogicContainerDelegate <NSObject>
- (void)threadLogicContainerDidStart:(ThreadLogicContainer*)theThreadLogicContainer;
- (void)threadLogicContainerDidFinish:(ThreadLogicContainer*)theThreadLogicContainer;
@end

@interface ThreadLogicContainer

- (void)doWorkWithDelegate:(id<ThreadLogicContainerDelegate>)delegate;

@end

@implementation ThreadLogicContainer

- (void)doWorkWithDelegate:(id<ThreadLogicContainerDelegate>)delegate
{
    @autoreleasepool
    {
        [delegate threadLogicContainerDidStart:self];

        // do work

        [delegate threadLogicContainerDidFinish:self];
    }
}

@end


@interface MyDelegate <ThreadLogicContainerDelegate>
@end

@implementation MyDelegate
- (void)threadLogicContainerDidStart:(ThreadLogicContainer*)theThreadLogicContainer
{}
- (void)threadLogicContainerDidFinish:(ThreadLogicContainer*)theThreadLogicContainer
{}
@end

示例用法:

ThreadLogicContainer* threadLogicContainer = [ThreadLogicContainer new];
[NSThread detachNewThreadSelector:@selector(doWorkWithDelegate:)
                         toTarget:threadLogicContainer
                        withObject:myDelegate];

参考:http: //developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html

于 2011-11-15T03:44:49.237 回答