Reputation: 754
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
.
#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.
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. Is that some kind of strange void pointer double cast?
I have no documentation with the code base I'm working with, so my guess is as good as the next guys'.
Upvotes: 0
Views: 1183
Reputation: 22152
std::thread
's constructor will start the new thread with the function and arguments provided.
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:
class ServerThread {
std::thread thr;
ServerThread() : thr() {
}
void StartThread(int arg1, double arg2) {
thr = std::thread(thread_func, arg1, arg2);
}
};
Upvotes: 3