繁体   English   中英

如何验证pthread函数是否开始执行

[英]How to verify if a pthread function began execution

例:

void start(void)
{
   pthread_create(&threadID, Null, run_thread_function,arguments);

   //is there a way to ensure if the run_thread_function(basically new thread) started   
   //execution before returning from this(start) function    

}

检查返回码。

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

作为参数的一部分传递一个同步对象(condvar,事件或信号量)。 在调用pthread_create()之后等待它。 在线程中,在第一行中(或在线程执行了其初始化工作之后,如果这是您要实现的目标)发出信号。

检查pthread_create函数的返回码是否有错误。

更新一些共享变量并从另一个线程对其进行测试。 记住在更新共享变量时要使用同步原语,例如互斥锁。

为了进行简单测试,请打印一些带有线程ID或其他标识符的消息。

在C ++ 11中,直到新线程启动后,才会通过std::thread类型的对象创建线程。

如果要确定新线程已经开始,请使用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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM