2012-10-31 34 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; 
} 
相关问题