gag*_*eet 4 c++ multithreading boost-bind boost-thread
希望同时多次调用函数.我希望使用线程来调用一个能充分利用机器功能的功能.这是一台8核机器,我的要求是使用10%到100%或更高的机器CPU.
我的要求是使用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;
}
Run Code Online (Sandbox Code Playgroud)
以上是行不通的,我不知道为什么?:-(
我建议您阅读有关您使用的功能的文档.根据您在James Hopkin的回答中的评论,您似乎不知道boost :: bind的作用,而只是复制粘贴代码.
boost :: bind接受一个函数(称之为f),以及可选的多个参数,并返回一个函数,该函数在被调用时使用指定的参数调用f.
也就是说,boost::bind(threadedAPI1, 0)()
(创建一个不带参数的函数,并使用参数0调用threadedAPI1(),然后调用它)相当于threadedAPI1(0)
.
由于您的threadedAPI函数实际上不接受任何参数,因此您无法将任何参数传递给它们.这只是基本的C++.你不能threadedAPI1(0)
只调用,但是threadedAPI1()
当你调用函数时,你尝试(通过boost :: bind)传递整数0作为参数.
因此,对您的问题的简单回答是简单地定义threadsAPI1,如下所示:
int threadedAPI1(int i);
Run Code Online (Sandbox Code Playgroud)
但是,避免boost :: bind调用的一种方法是在启动线程时调用functor而不是free函数.声明一个这样的类:
struct threadedAPI {
threadedAPI(int i) : i(i) {} // A constructor taking the arguments you wish to pass to the thread, and saves them in the class instance.
void operator()() { // The () operator is the function that is actually called when the thread starts, and because it is just a regular class member function, it can see the 'i' variable initialized by the constructor
cout << "Thread" << i << endl; // No need to create 4 identical functions. We can just reuse this one, and pass a different `i` each time we call it.
}
private:
int i;
};
Run Code Online (Sandbox Code Playgroud)
最后,根据您的需要,普通线程可能比线程池更适合.通常,线程池只运行有限数量的线程,因此它可能会排队某些任务,直到其中一个线程完成执行.它主要用于有许多短期任务的情况.
如果您有一定数量的较长持续时间的任务,则可以为每个任务创建一个专用线程.
归档时间: |
|
查看次数: |
10455 次 |
最近记录: |