小编use*_*318的帖子

多线程不会提高递归c ++程序的性能

考虑这个递归的多线程程序:

#include <iostream>
#include <thread>

#define NUMTHREADS 4
using namespace std;

int g[NUMTHREADS];

thread t[NUMTHREADS];

void task1(int x)
{
    if(x+1<NUMTHREADS)
        t[x] = thread(task1, x+1);
    for(int i=0;i<100000000;i++)
        g[x]++;
    if(x+1<NUMTHREADS)
        t[x].join();
}

int main()
{
    task1(0);
    for(int i=0;i<NUMTHREADS;i++)
        cout<<g[i]<<" ";
}
Run Code Online (Sandbox Code Playgroud)

我期望线程开销是微不足道的,但事实上程序的运行时间随着线程数的增加呈线性增长.

这是我的6核cpu的一些时间:

NUMTHREADS = 1:

$ time ./a
100000000
real    0m0.330s
user    0m0.312s
sys     0m0.015s
Run Code Online (Sandbox Code Playgroud)

NUMTHREADS = 2:

$ time ./a
100000000 100000000
real    0m0.742s
user    0m1.404s
sys     0m0.015s
Run Code Online (Sandbox Code Playgroud)

NUMTHREADS = 3:

$ time ./a
100000000 100000000 100000000
real    0m1.038s
user …
Run Code Online (Sandbox Code Playgroud)

c++ concurrency

2
推荐指数
1
解决办法
1394
查看次数

标签 统计

c++ ×1

concurrency ×1