工作者线程iOS

我想在iPhone上创build一个后台线程,每10毫秒执行一些代码。 但是在我再次迷失在并发编程指南和苹果的线程编程指南之前,我想问一下这里的某个人能否帮我一把。 我想做的事:

  • 创build一个后台工作线程
  • 每10毫秒触发一次方法的执行。 (可能通过在该线程中使用NSTimer?)
  • 尽可能减less主应用程序线程的负载

根据我的理解,子类化NSThread并在这个子类中写入我自己的主要方法应该可以做到。 这样,我不使用NSTimer的更新间隔,但像这样:

 [NSThread sleepForTimeInterval: 0.01]; 

主线程和工作线程之间的排队机制也没有任何意义,因为工作线程应该反复执行相同的操作 – 直到停止。

问题是:如何configuration线程使用计时器? 我看不到如何将NSTimer附加到该工作线程运行循环?

你可以用你勾画的方法来做这个,但是你看过使用Grand Central Dispatch吗? 它可以使这一些更容易一些:

 dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(backgroundQueue, ^{ while ([self shouldKeepProcessingInBackground]) { [self doBackgroundWork]; usleep(1e4); } }) 

您也可以使用定时器调度源定期进行工作:

 dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, backgroundQueue); dispatch_source_set_timer(timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), 0.01*NSEC_PER_SEC, 0*NSEC_PER_SEC); dispatch_source_set_event_handler(timerSource, ^{ [self doBackgroundWork]; }); dispatch_resume(timerSource); 

NSRunLoop是缺less的链接。

你将不得不设置线程的运行循环来重复,或者你可以从线程的条目中控制它。 该线程托pipe定时器(如果定时器仍然存在,定时器将与运行循环一起死亡)。

NSRunLoop是一个非常小的类 – 检查它和相关的样本。

你可以很容易地使用GCD(大中央调度)。 首先创build一个将在后台调用的select器。 从这里调用任何你想要的方法。

 - (void)backgroundSelector { // do whatever you want to do [self performSelector:@selector(backgroundSelector) withObject:nil afterDelay:0.01]; } 

之后,就这样第一次开始这种方法

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ [self backgroundSelector]; }); 

让我知道这是否适合你。

如果你用NSThread来做,它非常简单和干净。 不需要子类。

 - (void)backgroundStuff { while (!self.cancelThread) { // do your work [NSThread sleepForTimeInterval:0.01]; } } 

只是一个普通的function。 cancelThread是你声明的成员variables。 从开始

 [NSThread detachNewThreadSelector:@selector(backgroundStuff) toTarget:self withObject:nil]; 

你可以用self.cancelThread = true来随时取消线程。