【问题标题】:Is there an std::thread_create like pthread_create?是否有像 pthread_create 这样的 std::thread_create ?
【发布时间】:2019-09-05 20:23:23
【问题描述】:

我正在这里工作一个项目,试图将一些 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 指针双重转换吗?

我没有关于我正在使用的代码库的文档,所以我的猜测和接下来的人一样好。

【问题讨论】:

  • 我猜最接近pthread_create 的方法是构造一个新的std::thread 对象。没有直接翻译。
  • (void*(*)(void *)) 正在从 void* 转换函数指针。这只是有条件地支持,并非所有平台都允许这样做。

标签: c++ pthreads stdthread


【解决方案1】:

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);
    }

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2011-04-03
    • 2012-06-08
    • 2011-02-07
    • 2015-01-03
    • 1970-01-01
    相关资源
    最近更新 更多