繁体   English   中英

有没有像pthread_create这样的std :: thread_create?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM