希望多次同時調用一個函數。我希望使用線程來調用一個將充分利用機器功能的函數。這是一個8核心機器,我的要求是使用機器cpu從10%到100%或更多。使用增強庫的多線程
我的要求是使用boost類。有什麼辦法可以使用boost線程或線程池來完成這個任務嗎?或者以其他方式來做到這一點?另外,如果我必須每次使用不同的參數調用多個函數(使用不同的線程),那麼執行此操作的最佳方法是什麼? [使用提升或不使用提升]以及如何?
#include <iostream>
#include <fstream>
#include <string.h>
#include <time.h>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
using namespace std;
using boost::mutex;
using boost::thread;
int threadedAPI1();
int threadedAPI2();
int threadedAPI3();
int threadedAPI4();
int threadedAPI1() {
cout << "Thread0" << endl;
}
int threadedAPI2() {
cout << "Thread1" << endl;
}
int threadedAPI3() {
cout << "Thread2" << endl;
}
int threadedAPI4() {
cout << "Thread3" << endl;
}
int main(int argc, char* argv[]) {
boost::threadpool::thread_pool<> threads(4);
// start a new thread that calls the "threadLockedAPI" function
threads.schedule(boost::bind(&threadedAPI1,0));
threads.schedule(boost::bind(&threadedAPI2,1));
threads.schedule(boost::bind(&threadedAPI3,2));
threads.schedule(boost::bind(&threadedAPI4,3));
// wait for the thread to finish
threads.wait();
return 0;
}
以上是不工作,我不知道爲什麼? :-(
它總是一個好主意,指定*如何*它是「不工作」。它不會做你想要的?它不編譯?你會得到什麼錯誤?你到底在哪裏得到它們? – jalf 2008-12-05 18:25:12