如何在新线程中运行静态函数? P>搜索论坛后,我遇到了一些答案,但我无法得到一个明确的答案,如何在C++中的一个新线程中运行静态方法。我主要关心的是启动线程的最佳方式是什么?(它是否也在另一个线程内部工作?) 哪个标题更适合使用?thread.h,pthread.h
我想创建一个新线程(当调用一个给定的方法时),并在这个线程内调用另一个函数。。。 有没有关于我如何处理这个问题的提示如何在新线程中运行静态函数? P>搜索论坛后,我遇到了一些答案,但我无法得到一个明确的答案,如何在C++中的一个新线程中运行静态方法。我主要关心的是启动线程的最佳方式是什么?(它是否也在另一个线程内部工作?) 哪个标题更适合使用?thread.h,pthread.h,c++,multithreading,C++,Multithreading,我想创建一个新线程(当调用一个给定的方法时),并在这个线程内调用另一个函数。。。 有没有关于我如何处理这个问题的提示 提前非常感谢你们 在线程中运行静态成员函数没有问题。只需使用与自由函数相同的std::thread: #include <thread> class Threaded { public: static void thread_func() {} }; int main() { std::thread t(Threaded::thread_func
提前非常感谢你们 在线程中运行静态成员函数没有问题。只需使用与自由函数相同的
std::thread
:
#include <thread>
class Threaded
{
public:
static void thread_func() {}
};
int main()
{
std::thread t(Threaded::thread_func);
t.join();
return 0;
}
#包括
类线程
{
公众:
静态无效线程_func(){}
};
int main()
{
std::thread t(Threaded::thread_func);
t、 join();
返回0;
}
当然,起始线程也可以从任何其他线程开始工作。对于符合C++11标准的编译器,您应使用
#include
。否则请看一看。它的用法类似。实现这一点的最佳OOPs方法是:
定义一个入口点(entryPoint()
),它将调用成员函数(myThreadproc()
)。入口点将启动线程并调用myThreadproc
。然后可以访问所有成员变量和方法
myClassA.h
class A
{
static void *entryPoint(void *arg);
void myThreadproc();
void myfoo1();
void myfoo2();
}
myClassA.cpp
void *A::entryPoint(void *arg)
{
A *thisClass = (A *)arg;
thisClass-> myThreadproc();
}
void A::myThreadproc()
{
//Now this function is running in the thread..
myfoo1();
myfoo2();
}
现在,您可以创建如下线程:
int main()
{
pthread_t thread_id;
pthread_create(&thread_id,NULL,(A::entryPoint),new A());
//Wait for the thread
return 0;
}
例如,假设静态函数有两个参数:
#include <boost/thread/thread.hpp>
void launchThread()
{
boost::thread t( &MyClass::MyStaticFunction, arg1, arg2 );
}
#包括
void launchThread()
{
boost::线程t(&MyClass::MyStaticFunction,arg1,arg2);
}
这需要链接到库。这是特定于操作系统的,或者至少在所有编译器实现std::thread之前是这样。(它是C++11的一部分)。您应该从C++语言的基础开始,理解“静态”的意思。这里是如何将静态成员传递到线程的解释:代码>代码:A::入口点< /代码>需要返回<代码> Value*/Cuff>。我认为您想在<代码>登录点< /COD>中调用<代码> MythRead进程>代码>是吗?是的,但我通常只在用户一段时间内不进行编辑时才进行编辑+1无论如何。