简体   繁体   中英

Is this simple c++ program multithreaded?

I am sort of new to C++, but I was wondering if this basic (and possibly sloppy) program is actually running multiple threads at a time or if it its just pooling:

This is a console application running in 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;
}

I notice when I run the code with thread t1(math1);thread t2(math2);t1.join();t2.join(); , it uses 25% total of my cpu for 3.5 seconds, but when I use

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

it uses ~13% of the CPU for almost 7 seconds.

Is this actually multithreading?

thread t1(math1); thread t2(math2); t1.join(); t2.join(); waits for t1 to finish while also running t2 . The math1 and math2 functions do the same thing, so they'll finish approx. at once, which is optimal (it could be just one function as well).

To the numbers you're seeing, you clearly have a CPU with 8 logical cores. The multithreaded version uses two hardware threads (2 / 8) = 25%, while single-threaded just one (1 / 8) = 12,5%. It also runs two times slower, simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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