我是 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();
运行代码时,它总共使用了我的 25% cpu 3.5秒,但是当我使用
thread t1(math1);
t1.join();
thread t2(math2);
t2.join();
它使用了大约 13% 的 CPU,持续了将近 7 秒。
这实际上是多线程吗?
最佳答案
线程 t1(math1);线程 t2(math2); t1.join(); t2.join();
等待 t1
完成,同时还运行 t2
。 math1
和 math2
函数做同样的事情,所以它们将完成大约。一次,这是最佳的(它也可以只是一个函数)。
根据您所看到的数字,您显然拥有一个具有 8 个逻辑内核的 CPU。多线程版本使用两个硬件线程 (2/8) = 25%,而单线程只使用一个 (1/8) = 12,5%。它的运行速度也慢了两倍,很简单。
关于c++ - 这个简单的 C++ 程序是多线程的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35614713/