如何在类函数内部创建线程? [英] How to create a thread inside a class function?
问题描述
我对C ++很陌生.
I am very new to C++.
我有一个类,我想在一个类的函数内创建一个线程.该线程(函数)将调用并访问类的函数和变量. 在开始时,我尝试使用Pthread,但仅在类外部工作,如果我想访问类函数/变量,则会遇到范围错误. 我看了一下Boost/thread,但这是不理想的,因为我不想将任何其他库添加到我的文件中(由于其他原因).
I have a class, and I want to create a thread inside a class's function. And that thread(function) will call and access the class function and variable as well. At the beginning I tried to use Pthread, but only work outside a class, if I want to access the class function/variable I got an out of scope error. I take a look at Boost/thread but it is not desirable because of I don't want to add any other library to my files(for other reason).
我做了一些研究,找不到任何有用的答案. 请举一些例子来指导我.非常感谢!
I did some research and cannot find any useful answers. Please give some examples to guide me. Thank you so much!
尝试使用pthread(但是我不知道如何处理我上面提到的情况):
Attempt using pthread(but I dont know how to deal with the situation I stated above):
#include <pthread.h>
void* print(void* data)
{
std::cout << *((std::string*)data) << "\n";
return NULL; // We could return data here if we wanted to
}
int main()
{
std::string message = "Hello, pthreads!";
pthread_t threadHandle;
pthread_create(&threadHandle, NULL, &print, &message);
// Wait for the thread to finish, then exit
pthread_join(threadHandle, NULL);
return 0;
}
推荐答案
您可以将静态成员函数传递给pthread,并将对象的实例作为其参数.这个成语是这样的:
You can pass a static member function to a pthread, and an instance of an object as its argument. The idiom goes something like this:
class Parallel
{
private:
pthread_t thread;
static void * staticEntryPoint(void * c);
void entryPoint();
public:
void start();
};
void Parallel::start()
{
pthread_create(&thread, NULL, Parallel::staticEntryPoint, this);
}
void * Parallel::staticEntryPoint(void * c)
{
((Parallel *) c)->entryPoint();
return NULL;
}
void Parallel::entryPoint()
{
// thread body
}
这是一个pthread示例.您可能可以轻松地将其改编为使用std :: thread.
This is a pthread example. You can probably adapt it to use a std::thread without much difficulty.
这篇关于如何在类函数内部创建线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!