繁体   English   中英

这个简单的c ++程序是多线程的吗?

[英]Is this simple c++ program multithreaded?

我是C ++的新手,但我想知道这个基本的(可能是草率的)程序是否实际上一次运行多个线程,或者它是否只是汇集:

这是在visual c ++ 2015中运行的控制台应用程序:

#include <string>
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <thread>
using namespace std;
#include <stdio.h>
int temp1 = 0;
int num1 = 0;
int temp2 = 0;
int num2 = 0;
void math1() {
    int running_total = 23;
    for (int i = 0; i < 999999999; i++)
    {
        running_total = 58 * running_total + i;
    }
}
int math2() {

    int running_total = 23;
    for (int i = 0; i < 999999999; i++)
    {
        running_total = 58 * running_total + i;
    }
    return 0;
}
int main()
{
    unsigned concurentThreadsSupported = std::thread::hardware_concurrency();
    cout << "Current Number of CPU threads: " << concurentThreadsSupported << endl;
    thread t1(math1);
    thread t2(math2);
    t1.join();
    t2.join();
    cout << "1: " << num1 << endl;
    cout << "2: " << num2 << endl;
    system("pause");
    return 0;
}

当我用thread t1(math1);thread t2(math2);t1.join();t2.join();运行代码时,我注意到thread t1(math1);thread t2(math2);t1.join();t2.join(); ,它使用我的cpu总共25%,持续3.5秒,但是当我使用时

thread t1(math1);
t1.join();
thread t2(math2);
t2.join();

它使用约13%的CPU几乎7秒。

这实际上是多线程吗?

thread t1(math1); thread t2(math2); t1.join(); t2.join(); 在运行t2时等待t1完成。 math1math2函数执行相同的操作,因此它们将完成约。 立刻,这是最佳的(它可能只是一个功能)。

对于您所看到的数字,您显然拥有一个具有8个逻辑核心的CPU。 多线程版本使用两个硬件线程(2/8)= 25%,而单线程只使用一个(1/8)= 12.5%。 它运行速度慢两倍,简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM