我想使用多线程调用一个函数几次(即 4 次)。使用 Solarian 程序员博客 ( https://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/ ) 中的示例,我编写了这个简单的 c++11 程序:
#include <iostream>
#include <thread>
#include <ctime>
#include <math.h>
#define PI 3.14159265358979323846
static const int num_threads = 4;
void call_from_thread(int tid) {
std::cout << log(2) - 0.5*log(2*PI) - log(1.05) - pow(2.3-0.5,2)/(2*pow(1.05,2))<<std::endl;
}
int main() {
std::thread t[num_threads];
std::clock_t start;
start = std::clock();
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
t[i] = std::thread(call_from_thread, i);
}
std::cout << "Launched from the main\n";
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
return 0;
}
当然,这个例子很简单,我在这里不需要多线程,因为函数总是返回相同的结果。但是,我打算稍微修改一下这个函数,以便在线程之间存在一些差异。运行这段代码时,我得到了类似的东西:
Time: 0.806 ms
现在,如果我修改上面的代码以只允许单线程代码,我有以下内容:
int main() {
std::thread t[num_threads];
std::clock_t start;
start = std::clock();
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
call_from_thread(i);
}
std::cout << "Launched from the main\n";
std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
return 0;
}
在这里,运行时间要短得多:
Time: 0.116 ms
所以,我的问题是,我可以使用多线程调用这个简单的函数几次,以加快我的代码速度吗?基本上,我想低于 0.116 毫秒。
另请注意,我是 C++ 和并行性方面的新手,如果我的问题看起来不相关,我深表歉意。
最佳答案
您可以(理论上)这样做,但请注意,创建新线程是一项复杂而繁重的操作(对于操作系统和标准 C++ 库而言)。在 Linux 上,std::thread
会用 pthread_create(3)使用 clone(2) (低水平 system call )。
在实践中(作为一个非常天真的经验法则),创建一个线程可能需要几毫秒,并且只有当该线程运行超过几毫秒时才值得。所以你可能想要 thread pool秒。请记住,基本操作(机器代码指令,例如执行 32 位加法)通常只需要几 纳秒(一百万纳秒就是一毫秒)。因此在现实生活中,只有在实现相当“复杂”的功能时才值得使用线程。
换句话说, threads是相当繁重的资源(例如,因为它们通常有自己的 call stack,通常为 1 兆字节,并且它们希望在您处理器的其他一些 core 上运行)。
关于c++ - 我可以使用多线程调用一个简单的函数几次吗? C++11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52792483/