C++多线程-多核CPU下的多线程

多核CPU下的多线程

没有出现多核之前,我们的CPU实际上是按照某种规则对线程依次进行调度的。在某一个特定的时刻,CPU执行的还是某一个特定的线程。然而,现在有了多核CPU,一切变得不一样了,因为在某一时刻很有可能确实是n个任务在n个核上运行。我们可以编写一个简单的open mp测试一下,如果还是一个核,运行的时间就应该是一样的。

#include <omp.h>  
#define MAX_VALUE 10000000  
  
double _test(int value)  
{  
    int index;  
    double result;  
  
    result = 0.0;  
    for(index = value + 1; index < MAX_VALUE; index +=2 )  
        result += 1.0 / index;  
  
    return result;  
}  
  
void test()  
{  
    int index;  
    int time1;  
    int time2;  
    double value1,value2;  
    double result[2];  
  
    time1 = 0;  
    time2 = 0;  
  
    value1 = 0.0;  
    time1 = GetTickCount();  
    for(index = 1; index < MAX_VALUE; index ++)  
        value1 += 1.0 / index;  
  
    time1 = GetTickCount() - time1;  
  
    value2 = 0.0;  
    memset(result , 0, sizeof(double) * 2);  
    time2 = GetTickCount();  
  
#pragma omp parallel for  
    for(index = 0; index < 2; index++)  
        result[index] = _test(index);  
  
    value2 = result[0] + result[1];  
    time2 = GetTickCount() - time2;  
  
    printf("time1 = %d,time2 = %d\n",time1,time2);  
    return;  
}  
多线程编程

为什么要多线程编程呢?这其中的原因很多,我们可以举例解决
1)有的是为了提高运行的速度,比如多核cpu下的多线程
2)有的是为了提高资源的利用率,比如在网络环境下下载资源时,时延常常很高,我们可以通过不同的thread从不同的地方获取资源,这样可以提高效率
3)有的为了提供更好的服务,比如说是服务器
4)其他需要多线程编程的地方等等

发布了1024 篇原创文章 · 获赞 810 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/103902596