2012-10-31 29 views

回答

4

檢查返回代碼。

if ((retcode = pthread_create(&threadID, Null, run_thread_function,arguments)) != 0) 
{ 
    //something went wrong 
} 
+0

這是否真正達到什麼OP要求? –

+0

是的,上面的語句/檢查只是保證創建一個線程而不是執行它!我對後者感興趣 – user1789710

3

檢查pthread_create函數的返回碼是否有錯誤。

更新一些共享變量並從另一個線程進行測試。請記住在更新共享變量時使用同步原語,例如互斥體。或者爲了進行簡單的測試,用線程ID或其他類型的標識符打印一些消息。

+0

我不明白 - 如果你打算使用OS同步原語(比如互斥量,但不是互斥量:),爲什麼還要花費在輪詢共享變量?爲什麼不從新線程發出一些事件/信號/變化信號? –

+0

是的,這也是可能的。 – phoxis

4

傳遞一個同步對象(condvar,event或semaphore)作爲參數的一部分。在調用pthread_create()之後等待它。在線程中,在第一行發出信號(或者在線程執行了init的東西之後,如果這是你想要實現的)。

+0

你也可以考慮使用屏障。 – Brady

0

使用C++ 11,通過類型爲std::thread的對象創建線程在新線程啓動之前不會返回。

0

如果您想確定您的新線程是否已經開始,請使用pthread_barrier_wait

雖然,我真的質疑這個問題。好像你在問競賽條件。

請注意,我應該檢查所有地方的返回值,我不是爲了簡潔明瞭。 嘆息

#include <iostream> 
#include <pthread.h> 
#include <unistd.h> 

void *newthread(void *vbarrier) 
{ 
    pthread_barrier_t *barrier = static_cast<pthread_barrier_t *>(vbarrier); 
    sleep(2); 
    int err = pthread_barrier_wait(barrier); 
    if ((err != 0) && (err != PTHREAD_BARRIER_SERIAL_THREAD)) { 
     ::std::cerr << "Aiee! pthread_barrier_wait returned some sort of error!\n"; 
    } else { 
     ::std::cerr << "I am the new thread!\n"; 
    } 
    return 0; 
} 

int main() 
{ 
    pthread_barrier_t barrier; 
    pthread_barrier_init(&barrier, NULL, 2); 
    pthread_t other; 
    pthread_create(&other, NULL, newthread, &barrier); 
    pthread_barrier_wait(&barrier); 
    ::std::cerr << "Both I and the new thread reached the barrier.\n"; 
    pthread_join(other, NULL); 
    return 0; 
} 

C++ 11沒有障礙。但障礙可以很容易地模擬,在一定程度上,使用條件變量:

#include <thread> 
#include <condition_variable> 
#include <iostream> 
#include <unistd.h> 

void runthread(::std::mutex &m, ::std::condition_variable &v, bool &started) 
{ 
    sleep(2); 
    { 
     ::std::unique_lock< ::std::mutex> lock(m); 
     started = true; 
     v.notify_one(); 
    } 
    ::std::cerr << "I am the new thread!\n"; 
} 

int main() 
{ 
    ::std::mutex m; 
    ::std::condition_variable v; 
    bool started = false; 
    ::std::thread newthread(runthread, ::std::ref(m), ::std::ref(v), ::std::ref(started)); 
    { 
     ::std::unique_lock< ::std::mutex> lock(m); 
     while (!started) { 
     v.wait(lock); 
     } 
    } 
    ::std::cerr << "Both I and the new thread are running.\n"; 
    newthread.join(); 
    return 0; 
} 
相關問題