[英]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.