Worker Thread iOS

前端 未结 4 927
野性不改
野性不改 2021-01-03 10:20

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 program

4条回答
  •  忘掉有多难
    2021-01-03 10:54

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

提交回复
热议问题