在特定线程上执行(部分)静态函数

时间:2016-02-18 11:07:57

标签: multithreading swift

我有一个函数(无论是静态函数还是完全没有函数的函数)和特定的线程

class AnyClass{
    static func foo(myThread: NSThread) {
        ....
        // I want this *blablabla* to be performed on myThread
        ....
    }
}

我该如何做到?

1 个答案:

答案 0 :(得分:0)

请勿使用线程,而是使用调度队列(Grand Central Dispatch)。请参阅Migrating away from threads上的Apple文档。

GCD的典型使用模式是:

class AnyClass{
    static func foo(queue: dispatch_queue_t) {
        ....

        let group = dispatch_group_create();
        dispatch_group_enter(group) // tell the OS your group has started
        dispatch_group_async(group, queue) {
            // Do your things on a different queue
            ....
            dispatch_group_leave(group) // tell the OS your group has ended
        }

        // Do your other things on the original thread simultaneously
        ....

        dispatch_group_wait(group, DISPATCH_TIME_FOREVER) // wait for the queue to finish

        // Do other things still
        ....
    }
}

// Calling the function
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
AnyClass.foo(queue)