[英]Is there an std::thread_create like pthread_create?
I'm working a project here trying to port some Linux C++ code to be cross platform, and I have here a wrapper thread class that's using pthread
. 我在这里工作的一个项目试图将一些Linux C ++代码移植到跨平台,并且这里有一个使用pthread
的包装线程类。
#include <pthread.h>
class ServerThread {
public:
pthread_t tid;
pthread_mutex_t mutex;
int Create (void* callback, void* args);
};
I'm trying to port this directly to std::thread
but the Create
method here uses pthread_create
which I understand starts the thread, but I'm unable to find the std
equivalent. 我试图将其直接移植到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;
}
I genuinely don't understand what I'm looking at with that pthread_create
function call. 我真的不明白我在用那个pthread_create
函数调用看什么。 Is that some kind of strange void pointer double cast? 这是某种奇怪的void指针两次转换吗?
I have no documentation with the code base I'm working with, so my guess is as good as the next guys'. 我没有正在使用的代码库的文档,所以我的猜测和下一个家伙一样。
std::thread
's constructor will start the new thread with the function and arguments provided. std::thread
的构造函数将使用提供的函数和参数启动新线程。
So roughly: 大致来说:
void thread_func(int, double) {
}
class ServerThread {
std::thread thr;
ServerThread(int arg1, double arg2)
: thr(thread_func, arg1, arg2) {
}
};
If you want to run the thread later after the construction, you can first default-initialize std::thread
, which will not start an actual thread, and then you can move a new std::thread
instance with started thread into it later: 如果要在构造后稍后运行线程,则可以先默认初始化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.