2011-10-30 76 views
3

我想执行上述操作。在线程中运行函数

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

线程依赖于操作系统。在不知道操作系统的情况下,我们只能建议您查看一些与平台无关的库,如boost和Qt。 – Juliano

+0

需要一个库或C++ 11 –

+0

对不起,我的错误,Windows 7 – Pumpkin

回答

4

对于Win32编程,您可以使用beginthread。也有CreateThread,但如果我没有记错,那不会初始化C/C++环境,这会导致问题。

编辑:刚刚选中 - MSDN声明“调用C运行时库(CRT)的可执行文件中的线程应该使用_beginthread和_endthread函数进行线程管理,而不是CreateThread和ExitThread”。

3

Boost.Thread

void myFunc() { 
    // ... stuff ... 
} 

int main() { 
    boost::thread<void()> t(&myFunc); 

    // ... stuff ... 

    t.join(); 
} 

或标准库等价物,如果你正在使用C++ 11。

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 

您将需要确保升压线程库已经建成。

使用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 
3

您还可以检查出开放多处理(OMP)协议。这是编写多线程程序的最简单方法(但仅适用于多CPU系统)。

例如,对于,当所有可访问的CPU将一起,可以在该方法中实现并行:

#pragma omp parallel for 
for(int i = 0; i < ARRAY_LENGH; ++i) 
{ 
    array[i] = i; 
} 
+0

虽然,也许使用'#pragma omp parallel'来启动几个并行运行的函数将是一个比for循环更好的例子。 –

+0

你拼错LENGTH。 –

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::asyncstd::launch::deferred`std::launch::async导致线程立即启动,当需要结果时,std::launch::deferred将启动线程,这意味着调用ftr.get()时,或者当ftr超出范围时。

+0

它是C++ 11,并且该代码必须位于功能块中。 –

+0

@Tomalak:当然你是对的。我解决了这个问题,并改变了代码使用'std :: async'而不是'std :: thread',因为这是在一个线程中运行一个函数(可能返回一个值)的最简单的方法。 – smerlin

+0

这是他们称之为期货吗?我还没有看过这个东西。 –