我想执行上述操作。
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.
...
}
你有什么建议我该做什么?哪个函数调用哪个库可以让我完成目标?
答案 0 :(得分:4)
对于Win32编程,您可以使用beginthread
。还有CreateThread
,但是如果我没记错的话,那就不会初始化C / C ++环境,这会导致问题。
编辑:刚检查 - MSDN声明“调用C运行时库(CRT)的可执行文件中的线程应使用_beginthread和_endthread函数进行线程管理,而不是CreateThread和ExitThread”。
答案 1 :(得分:3)
void myFunc() {
// ... stuff ...
}
int main() {
boost::thread<void()> t(&myFunc);
// ... stuff ...
t.join();
}
如果您使用的是C ++ 11,则可以使用标准库。
答案 2 :(得分:3)
您也可以查看开放式多处理(OMP)协议。这是编写多线程程序的最简单方法(但仅适用于多CPU系统)。
例如,并行,当所有可访问的CPU一起工作时,可以以这种方式实现:
#pragma omp parallel for
for(int i = 0; i < ARRAY_LENGH; ++i)
{
array[i] = i;
}
答案 3 :(得分:2)
适用于Windows _beginthread
或_beginthreadex
MSDN Documentation of the two.
另请参阅此库有关线程的信息:The Code Project article on Multi-threading
答案 4 :(得分:2)
需要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
超出范围时。
答案 5 :(得分:1)
使用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