2016-08-10 132 views
0

我明確創建了一個帶NSThread類的工作線程。NSThread,停止並等待2秒

NSThread *workerThread = [[NSThread alloc] initWithTarget:self 
                selector:@selector(doWork) 
                 object:nil]; 
[workerThread start]; 

我知道有在NSThread沒有「加入」功能,是什麼阻止這個線程&等待2秒鐘線程死亡的最好方法? (像Java線程join(2000)功能)

[workerThread cancel] 
//how to wait for 2 seconds for the thread to die? I need something like join(2000) in Java 

(請不要說話GCD,我的問題是關於NSThread,謝謝。)

+1

什麼這個問題:http://stackoverflow.com/questions/7952653/sleep-or-pause-nsthread? – flashspys

+0

@flashspys,顯然這個鏈接與我的問題無關。它談到讓線程睡眠,我的問題是關於等待線程被殺死。如果您檢查我的問題中鏈接的Java join()函數的文檔,您將瞭解我需要的內容。 –

+0

我讀過「死去」了,對不起。我認爲沒有使用gcd或NSOperationQueue是不可能的。 NSThread的API不是很廣泛。 – flashspys

回答

0

回採程序線程是不是一個好主意恕我直言,如果可能的話,不知道蘋果那樣的,但你可以得到一個解決辦法...

我看到了這樣的方式:

1 /快速和骯髒的NSTimer將檢查每一個X秒線程的狀態,不是我的杯子的茶雖然。

2 /在你的doWork選擇職位時的作業做了NSNotification,並註冊它,當它發射了,你知道你的線程完成...

我愛2號更好的解決方案,是的,所以這裏GCD ROX是我怎麼會做:

static NSThread * workerThread; 

- (void) startWorkerThread 
{ 
    workerThread = [[NSThread alloc] initWithTarget:self selector:@selector(doWork) object:nil]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(workerThreadDidReturn) name:@"workerThreadReturnsNotification" object:nil]; 
    [workerThread start]; 

    static NSInteger timeoutSeconds = 5; 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
     // Cancel after timeoutSeconds seconds if not finished yet 
     if(![workerThread isCancelled]){ 
      [workerThread cancel]; 
     } 
    }); 

} 

- (void) doWork 
{ 

    // Do something heavy... 
    id result = [NSObject new]; 

    [[NSNotificationCenter defaultCenter] postNotificationName:@"workerThreadReturnsNotification" 
                 object:result]; 
} 


- (void) workerThreadDidReturn:(NSNotification *)notif 
{ 
    id result = (id) notify.object; 
    // do something with result... 

    [workerThread cancel]; 
}