小编pag*_*ist的帖子

循环变量生命周期的C++很奇怪

for(int i = 0; i < 3; i++)
{
    for(int j = 0; j < 3; j++)
    {
        int n;
        n++;
        printf("n : %d\n", n)'
    }
}
Run Code Online (Sandbox Code Playgroud)

代码的输出是1 2 3 4 5 6 7 8 9.我想知道为什么在执行变量声明时for循环中的变量n没有被初始化.

c++ variables scope initialization lifetime

5
推荐指数
1
解决办法
480
查看次数

数组的并行求和比C++中的序列求和要慢

我用C++ std :: thread编写了数组并行求和的代码.但平行和需要0.6s,顺序总和需要0.3s.

我不认为这个代码在arr或上进行任何同步ret.

为什么会出现这种情况?

我的CPU是i7-8700,有6个物理内核.

#include <stdio.h>
#include <ctime>
#include <thread>

// Constants
#define THREADS 4
#define ARR_SIZE 200000000
int ret[THREADS];

// Function for thread.
void parallel_sum(int *arr, int thread_id) {
    int s = ARR_SIZE / THREADS * thread_id, e = ARR_SIZE / THREADS * (thread_id + 1);
    printf("%d, %d\n", s, e);
    for (int i = s; i < e; i++) ret[thread_id] += arr[i];
}

int main() {

    // Variable definitions
    int *arr = …
Run Code Online (Sandbox Code Playgroud)

c++ parallel-processing multithreading

3
推荐指数
1
解决办法
136
查看次数