近日,在看一個C语言代碼的時候,看到了多進程的相關案例,但是在自己嘗試的時候,按照網上的教程,發現教程内容不能正常使用,特提出解決方法:

#include <iostream>
#include <omp.h>


using namespace std;

static int i = 0;
void PlayOjbk()
{







//设置线程数,一般设置的线程数不超过CPU核心数,这里开四个线程执行并行代码段
//omp_set_num_threads(4);
omp_set_num_threads(8);
#pragma omp parallel
{
//用cout输出会混乱
//cout << "hello!!!" << "I am Thread " << omp_get_thread_num() << "\n" << endl;
printf("i = %d, I am Thread %d \n", i, omp_get_thread_num());
i++;
}
printf("omp_get_num_procs(void):%d\n", omp_get_num_procs());
printf("omp_get_num_threads(void):%d\n", omp_get_num_threads());




}


int main(int argc, char **argv)
{


PlayOjbk();


printf("i:%d\n", i);


system("pause"); 
// return 0;
}



按照上面的代碼,申請了八個進程,實際上只開闢了一個進程,解決這個問題的方案是:

打開項目屬性,依次選擇->配置属性->C、C++ -> 语言 ->OpenMP支持 ,选是。

解決在C語言,C++語言下使用多綫程Omp,申請進程不成功問題


设置之前运行效果:

解決在C語言,C++語言下使用多綫程Omp,申請進程不成功問題

设置之后运行效果:

解決在C語言,C++語言下使用多綫程Omp,申請進程不成功問題

可成功申请8个进程


相关文章: