工人线程iOS [英] Worker Thread iOS

查看:71
本文介绍了工人线程iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iPhone上创建一个后台线程,每10毫秒执行一些代码。
但是在我迷失并发编程指南和苹果的线程编程指南之前,我想问一下这里有人可以帮助我。
我想做什么:

I want to create a background thread on the iPhone that executes some code every 10msec. But before I get lost in the concurrency programming guide and the threading programming guide of apple again, I wanted to ask whether someone here can help me out. What I want to do:


  • 创建后台工作线程

  • 触发每10毫秒执行一次方法。 (可能是通过在该线程中使用NSTimer?)

  • 尽量减少主应用程序线程的负载

在我的理解中,继承 NSThread 并在该子类中编写我自己的main方法应该可以解决问题。这样我就不会使用 NSTimer 来获取更新间隔,例如:

In my understanding subclassing NSThread and writing my own main method in that subclass should do the trick. That way I don't use an NSTimer for the update intervals but something like:

[NSThread sleepForTimeInterval: 0.01];

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

Also queuing mechanisms between main thread and worker thread don't make any sense, as the worker thread should perform the same operation over and over - until stopped.

问题是:如何配置线程使用计时器?我看不出如何将 NSTimer 附加到该工作线程Run Loop?

The question is: How can I configure the thread to use a timer? I can't see how I can attach a NSTimer to that worker threads Run Loop?

推荐答案

使用你概述的方法可以做到这一点,但是你看过使用Grand Central Dispatch吗?它可以使其中的一些变得更容易:

It's possible to do this using the method you outline, but have you looked at using Grand Central Dispatch? It can make some of this a lot easier:

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

您还可以使用定时器调度源定期工作:

You can also use a timer dispatch source to do work periodically:

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);

这篇关于工人线程iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆