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
}
检查pthread_create
函数的返回码是否有错误。
更新一些共享变量并从另一个线程进行测试。请记住在更新共享变量时使用同步原语,例如互斥体。或者为了进行简单的测试,用线程ID或其他类型的标识符打印一些消息。
我不明白 - 如果你打算使用OS同步原语(比如互斥量,但不是互斥量:),为什么还要花费在轮询共享变量?为什么不从新线程发出一些事件/信号/变化信号? –
是的,这也是可能的。 – phoxis
传递一个同步对象(condvar,event或semaphore)作为参数的一部分。在调用pthread_create()之后等待它。在线程中,在第一行发出信号(或者在线程执行了init的东西之后,如果这是你想要实现的)。
你也可以考虑使用屏障。 – Brady
使用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;
}
- 1. 如何在开始执行其他功能之前完成功能执行
- 2. Javascript验证功能未执行
- 3. apex始终执行验证
- 4. 如何让一个线程等待并执行另一个?
- 5. 验证并执行公式?
- 6. 上一个功能运行完成后执行一个功能
- 7. 执行并行线程池
- 8. 如何测试验证特定功能是否执行
- 9. 硒网格,测试开始在同一线程并行运行时开始
- 10. 为什么线程在另一个线程开始执行时会停止?
- 11. 如何在另一个功能完成后执行功能?
- 12. 如何在完成第一个功能后执行功能?
- 13. 2功能并排执行
- 14. 并行线程功能 “_np” 后缀
- 15. CUDA。如何展开前32个线程,以便它们并行执行?
- 16. 绑定功能,所以当一个执行另一个执行
- 17. 开始执行
- 18. 如何开始在WPF应用程序中执行计时器功能
- 19. 将执行从一个线程移动到另一个线程以执行任务并行和调用
- 20. 读取一个文件并根据行内容执行功能
- 21. 我如何执行功能?
- 22. 同时开始的两个并行请求一个接一个地执行
- 23. 如何让红宝石线程执行我选择的功能?
- 24. 执行功能,有条件和并行
- 25. 异步和并行执行的功能
- 26. 如何并行执行一个函数?
- 27. Passport身份验证始终执行failureRedirect
- 28. 如何等待当前线程执行,并执行其他线程completedly
- 29. 在执行PostExecution后,doInBackground中的AsycTask线程开始运行
- 30. 如何在另一个线程组中执行线程组?
这是否真正达到什么OP要求? –
是的,上面的语句/检查只是保证创建一个线程而不是执行它!我对后者感兴趣 – user1789710