C++:使用pthread_create创建新线程,以运行类成员函数
C++: Creating new thread using pthread_create, to run a class member function
我有以下类:
class A
{
private:
int starter()
{
//TO_DO: pthread_create()
}
void* threadStartRoutine( void *pThis );
}
我想从starter()内部创建一个线程来运行threadStartRoutine()。我得到了关于第三个参数的编译时错误,它应该采用启动例程的地址。
调用pthread_create()来创建一个开始执行threadStartRoutine()的新线程的正确方法是什么?
我在网上看到一些文章说,大多数编译器不允许使用pthread_create()调用非静态成员函数。这是真的吗?这背后的原因是什么?
我正在使用G++在Linux-x64上编译我的程序。
将threadStartRountine()
声明为static
:
static void* threadStartRoutine( void *pThis );
否则,threadStartRoutine()
的类型为:
void* (A::*)(void*)
这不是CCD_ 4所需要的函数指针的类型。
使用pthreads有原因吗?c++11在这里,为什么不直接使用它:
#include <iostream>
#include <thread>
void doWork()
{
while(true)
{
// Do some work;
sleep(1); // Rest
std::cout << "hi from worker." << std::endl;
}
}
int main(int, char**)
{
std::thread worker(&doWork);
std::cout << "hello from main thread, the worker thread is busy." << std::endl;
worker.join();
return 0;
}
只需使用一个普通函数作为包装器。正如hjmd所说,静态函数可能是最好的一种正常函数。
如果您坚持使用原生pthreads接口,那么必须提供一个普通函数作为入口点。一个典型的例子:
class A
{
private:
int starter()
{
pthread_t thr;
int res = pthread_create(&thr, NULL, a_starter, this);
// ...
}
public:
void run();
};
extern "C" void * a_starter(void * p)
{
A * a = reinterpret_cast<A*>(p);
a->run();
return NULL;
}
相关文章:
- 为什么std::async使用同一个线程运行函数
- 如何在 qt 中从另一个线程运行 qt并发时关闭程序
- 如何使线程运行现有类的函数?C++
- 使用 4 个和 8 个线程运行时执行的时间相等
- 在我调用join()之前,std ::线程运行
- winsock连接调用崩溃如果多个线程运行,则在一个线程中正常工作
- 如何确保这部分代码仅由一个线程运行(在 openmp 中)
- 线程连接在另一个线程运行时会导致分段错误
- 动态提升线程运行存储在具有共享指针的向量中的对象的方法
- 如何启动一个 boost::线程运行一个成员函数
- 如果由另一个 OpenMP 程序调用,则外部调用的 OpenMP 程序仅使用一个线程运行
- 线程运行时间最少
- 计算线程运行的次数
- MySQL C API:从不同线程运行查询时出现分段错误
- 使用两个线程运行和中断一个无限循环
- 与icc 14一起使用多线程运行时库时的错误
- 为什么我得到无限循环只有线程# 0后,所有5个线程运行多线程c++用餐哲学家谜语
- 发布配置上的Visual Studio c++多线程运行时问题
- 使用逻辑线程运行程序
- 为什么设置 CPU 关联会使线程运行速度变慢