Multithreading in c++

后端 未结 6 2058
轮回少年
轮回少年 2020-12-15 13:48

I want to run one function with different parameters on different threads:

int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i&l         


        
6条回答
  •  醉话见心
    2020-12-15 14:44

    Since OpenMP is supported in Visual studio why not use that? It's far simpler than managing your own threads manually, is very portable and the example you gave is almost perfect for it. Wikipedia has a reasonble introduction to the concepts of OpenMP.

    In your example the simple (and slightly naive - normally you don't explicitly say the number of threads, you say the number of work units) code is:

    int threads = 3;
    int par1[] = {1, 2, 3};
    int par2[] = {4, 5, 6};
    #pragma omp parallel for
    for (int i=0; i

    With an appropriate option passed to the compiler to enable OpenMP. Without this option it still compiles and runs as a serial program too.

提交回复
热议问题