![](/img/trans.png)
[英]The argument of pthread_create was used in C++ — Every time the thread function get the value was the same, why?
[英]Passing a C++ function object to pthread_create function as the thread routine
我知道傳遞給pthread_create API的線程例程具有原型
void *threadproc(void *).
我只是想知道是否可以使用C ++函數對象作為線程例程。
這是我的代碼:
Execution :: run方法將time_t變量和仿 函數作為參數。 它產生一個POSIX線程,在該線程中它旋轉直到預定的運行時間是最新的並運行一些工作。
#include <pthread.h>
#include <ctime>
#include <unistd.h>
#include <iostream>
using namespace std;
class ThreadFunctor
{
public:
void *operator()(time_t runTime)
{
time_t curTime;
double timeDiff;
time(&curTime);
timeDiff = difftime(runTime, curTime);
if (timeDiff > 0)
{
sleep(timeDiff);
}
//
// doSomething();
//
return NULL;
}
};
class Execution
{
public:
Execution() {}
int run(time_t scheduledTime, ThreadFunctor &threadProc)
{
int rc = pthread_create(&mThread, NULL, threadProc, &scheduledTime);
if (rc != 0)
{
cerr << "Thread creation failed\n";
return -1;
}
return 0;
}
private:
pthread_t mThread;
};
問題:
我可以使用函數對象作為線程函數嗎? 怎么樣?
如何將參數傳遞給函數對象的operator()方法?
在此代碼中,父進程在子線程仍在運行時終止。 因為我們不想阻止run()方法的調用者。 這是一個好習慣嗎? 孤兒線程會在這里引起問題嗎?
謝謝。
pthread函數必須具有C鏈接,因此它不能是成員函數。 嚴格來說,它甚至不能成為靜態成員函數,即使它幾乎一直都可以工作。
所以應該做的是創建一個非成員函數,它接受一個void*
參數,該參數將是一個指向C ++對象的指針作為線程函數。 該函數可以將void*
參數轉換為類指針,該類指針調用成員函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.