在线程中运行函数

Running a function in a thread

本文关键字:函数 运行 线程      更新时间:2023-10-16

我想执行上述操作。

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::asyncstd::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