2012-04-18 49 views
2

我想多次調用具有不同arg值的函數。爲了更快地執行,我想調用函數而不考慮它的實現。多次並行調用函數

在一個循環中,我將arg傳遞給函數並調用它,現在我的程序不應該等待函數執行並再次循環,而應該不考慮該函數未完成第一個循環向前並一次又一次地調用該函數直到循環結束。

如何使用fork和線程來做到這一點,哪一個會更快,代碼的骨架會有所幫助? 假設我的函數是void foo(arg1,arg2)

回答

2

如果它是一種計算密集型方法,那麼爲每個調用產生一個線程/進程並不是一個好主意(事實上,它從來不是一個好主意!)。

可以有效地並行for循環使用OpenMP:

#pragma omp parallel for 
for(int i = 0; i < N; i++) 
{ 
    int arg1 = ... 
    int arg2 = ... 
    foo(arg1, arg2); 
} 

這將創建一個線程數根據可用的CPU核心數量,然後它們之間拆分迭代。您可以使用schedule子句進一步調整計劃。

+0

的函數調用的腳本由此帶來向上/向下daemons.The腳本花費大量的時間去完成了,所以我想實例化腳本並等待它們完成 – Kimi 2012-04-18 20:59:55

1

你想異步執行的proactor pattern.

下面是一個例子,使用boost::asioboost::thread

#include <iostream> 
using namespace std; 

#include <boost/asio.hpp> 
#include <boost/thread.hpp> 

// your function, with its arguments 
void foo(int x, int y) 
{ 
    cout << x << " * " << y << " = " << x * y << "\n"; 
} 

int main() 
{ 
    boost::asio::io_service svc; 
    boost::asio::io_service::work w(svc); 

    // create a thread to run the io_service proactor 
    boost::thread thread(boost::bind(&boost::asio::io_service::run, &svc)); 

    for(int z = 0; z < 32; ++z) 
    { 
     // bind the function to its arguments to 
     // be called in the context of the running 
     // thread 
     svc.post(boost::bind(&f, 2, z)); 
    } 

    boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); 

    svc.stop(); 
    thread.join(); 
} 

這樣做的好處,是可以通過,如果線程池調用boost::asio::io_service::run輕鬆擴展必要。

1

就像都鐸王朝推薦的那樣,我也會使用Intel TBB或Microsoft PPL的parallel_for模式算法。

如果你真的想產生一個線程需要爲每一個功能,你可以做這樣的:

#include <thread> 
#include <vector> 

void foo(arg1, arg2) { 
    //do stuff 
} 

int main() { 

    std::vector<std::thread> threads; 

    for(auto i = x; i != y; ++i) 
    threads.emplace_back(foo, arg1, arg2); 

    for(auto& i: threads) 
    i.join(); 

} 
+0

如何使用fork實現此操作? – Kimi 2012-04-19 13:30:24