[英]Is there an std::thread_create like pthread_create?
我在這里工作的一個項目試圖將一些Linux C ++代碼移植到跨平台,並且這里有一個使用pthread
的包裝線程類。
#include <pthread.h>
class ServerThread {
public:
pthread_t tid;
pthread_mutex_t mutex;
int Create (void* callback, void* args);
};
我試圖將其直接移植到std::thread
但是此處的Create
方法使用了pthread_create
,據我了解該線程啟動了線程,但是我找不到等效的std
。
int ServerThread :: Create (void* callback, void* args) {
int tret = 0;
tret = pthread_create(&this->tid, nullptr, (void*(*)(void *)) callback, args);
if (tret != 0) {
std::cerr << "Error creating thread." << std::endl;
return tret;
}
return 0;
}
我真的不明白我在用那個pthread_create
函數調用看什么。 這是某種奇怪的void指針兩次轉換嗎?
我沒有正在使用的代碼庫的文檔,所以我的猜測和下一個家伙一樣。
std::thread
的構造函數將使用提供的函數和參數啟動新線程。
大致來說:
void thread_func(int, double) {
}
class ServerThread {
std::thread thr;
ServerThread(int arg1, double arg2)
: thr(thread_func, arg1, arg2) {
}
};
如果要在構造后稍后運行線程,則可以先默認初始化std::thread
,它不會啟動實際的線程,然后可以在以后將帶有已啟動線程的新std::thread
實例移入該線程:
class ServerThread {
std::thread thr;
ServerThread() : thr() {
}
void StartThread(int arg1, double arg2) {
thr = std::thread(thread_func, arg1, arg2);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.