gpt4 book ai didi

c++ - 使用 boost 库的多线程

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:06:03 26 4
gpt4 key购买 nike

希望同时多次调用一个函数。我希望使用线程来调用一个函数,该函数将最大限度地利用机器的功能。这是一台8核机器,我的要求是机器cpu使用率从10%到100%或者更多。

我的要求是使用 boost 类。有什么方法可以使用 boost 线程或线程池库来完成此操作?或者其他方法?

此外,如果我每次都必须调用具有不同参数的多个函数(使用单独的线程),执行此操作的最佳方法是什么? [使用 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;
}

上面的方法不起作用,我不确定为什么? :-(

最佳答案

我建议您阅读所用函数的文档。从您对 James Hopkin 的回答的评论来看,您似乎不知道 boost::bind 做了什么,只是简单地复制粘贴了代码。

boost::bind 接受一个函数(称之为 f)和可选的一些参数,并返回一个函数,该函数在被调用时使用指定的参数调用 f。

也就是说,boost::bind(threadedAPI1, 0)()(创建一个不带参数的函数并使用参数 0 调用 threadedAPI1(),然后调用它)等同于threadedAPI1(0)

由于您的 threadedAPI 函数实际上不接受任何参数,因此您不能向它们传递任何参数。那只是基本的 C++。您不能调用 threadedAPI1(0),只能调用 threadedAPI1(),但是当您调用该函数时,您尝试(通过 boost::bind)传递整数 0 作为参数。

因此,您的问题的简单答案是简单地定义 threadedAPI1,如下所示:

int threadedAPI1(int i);

但是,避免 boost::bind 调用的一种方法是在启动线程时调用仿函数而不是自由函数。像这样声明一个类:

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;
};

最后,根据您的需要,普通线程可能比线程池更适合。通常,线程池只运行有限数量的线程,因此它可能会排队一些任务,直到其中一个线程执行完毕。它主要用于您有许多短期任务的情况。

如果您有固定数量的持续时间较长的任务,为每个任务创建一个专用线程可能是可行的方法。

关于c++ - 使用 boost 库的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/344101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com