在线程中运行函数
Running a function in a thread
我想执行上述操作。
void myFunc()
{
... // several stuff
}
...
int main()
{
...
// I would like to run myFunc in a thread so that the code below could execute
// while it is being completed.
...
}
你建议我该怎么做?从哪个库调用哪个函数可以使我完成我的目标?
对于Win32编程,可以使用beginthread
。还有CreateThread
,但如果我没记错的话,它不会初始化C/c++环境,这会导致问题。
编辑:刚刚检查- MSDN状态"一个线程在可执行程序调用C运行时库(CRT)应该使用_beginthread和_endthread函数进行线程管理,而不是CreateThread和ExitThread"
Boost.Thread.
void myFunc() {
// ... stuff ...
}
int main() {
boost::thread<void()> t(&myFunc);
// ... stuff ...
t.join();
}
您还可以查看开放多处理(OMP)协议。这是编写多线程程序最简单的方法(但只适用于多CPU系统)。
例如,当所有可访问的cpu一起工作时,parallel For可以这样实现:
#pragma omp parallel for
for(int i = 0; i < ARRAY_LENGH; ++i)
{
array[i] = i;
}
For Windows _beginthread
或_beginthreadex
两者的MSDN文档
还可以看看这个关于线程的库:Code Project关于多线程的文章
需要c++11(以前称为c++0x)支持:
#include <future>
int main(int argc, char* argv[])
{
auto ftr = std::async( std::launch::async, [](){
//your code which you want to run in a thread goes here.
});
}
启动策略可以是std::launch::async
或std::launch::deferred
。`std::launch::async
使线程立即启动,std::launch::deferred
将在需要结果时启动线程,这意味着当ftr.get()
被调用时,或者当ftr
超出作用域时。
使用boost/thread:
#include <boost/thread.hpp>
void myFunc()
{
// several stuff
}
int main()
{
boost::thread thread(myFunc);
// thread created
//...
// I would like to run myFunc in a thread so that the code below could execute
// while it is being completed.
//...
// must wait for thread to finish before exiting
thread.join();
}
> g++ -lboost_thread test.cpp
您需要确保boost线程库已经构建。
使用pthreads:void* myFunc(void* arg)
{
// several stuff
return NULL;
}
int main()
{
pthread_t thread;
int result = pthread_create(&thread, NULL, myFunc, NULL);
if (result == 0)
{
// thread created
//...
// I would like to run myFunc in a thread so that the code below could execute
// while it is being completed.
//...
// must wait for thread to finish before exiting
void* result;
pthread_join(thread, &result);
}
}
> g++ -lpthread test.cpp
相关文章:
- 如何在函数运行时逐个显示列表项
- C++:链接库两次,全局构造函数运行两次吗?
- C 从类的构造函数运行Boost线程
- 回文过滤器,函数运行良好,但main()无法编译
- 如何在 c++ 中将机器代码作为函数运行
- 将 PHP 中的 $_POST 变量传递给由 exec() 函数运行的C++程序
- 如何在 C++ 中使用一个 System() 函数运行 2 个命令
- 为什么用空函数运行std::线程会花费大量内存
- 在函数运行时停止 Wt C++函数
- C 构造函数运行时/编译时间
- 是否可以在析构函数运行时不销毁 obj
- CArray的析构函数运行大约需要30秒
- 如何使这个递归函数运行得更快
- 如何在Visual studio C++中检查函数运行时间
- C++函数运行,即使它不应该运行?
- 参数的可变数量函数运行时错误
- boost::asio::io_service析构函数运行很长时间
- 具有变量参数的函数运行时错误
- C++析构函数运行时错误:无法munmap
- 如何在 MEX 函数运行时制作它 printf?