Why is a single thread faster than multiple threads, although they essentially have the same overhead?

I am running 64-bit Windows 7 on an 8-core processor. I ran the following:

    #include "stdafx.h"
    #include <iostream>
    #include <Windows.h>
    #include <process.h>
    #include <ctime>

    using namespace std;

    int count = 0;
    int t = time(NULL);

    //poop() loops incrementing count until it is 300 million.
    void poop(void* params) {
        while(count < 300000000) {
            count++;
        }


        cout<< time(NULL) - t <<" \n";
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
        //_beginthread(poop, 0, NULL);      
        //_beginthread(poop, 0, NULL);
        poop(NULL);

        cout<<"done"<<endl;

        while(1);

        return 0;
    }

I compared the result with when I uncommented beginThread. It turns out that the single-thread version achieves this fastest! In fact, adding more threads makes the process even longer. Accounting for 300 million made the process take 8+ seconds, which I thought was good enough to exclude calls to the beginThread function + other minor overhead.

, - , . , , , ( , afaik), . , , ( ) , , .

, 13% ( 1/8 ), 1/8 . , , , , CPU. ... , , ?

TL;DR:

+5
2

.

count++ - , , , .
count++ , , .

, , .

count , .

, , .

+5

, . -, . , , 300 . , count poop

void poop(void* params) {
    int count  = 0;
    while(count < 300000000) {
        count++;
    }
    cout<< time(NULL) - t <<" \n";
}

, t, , . cout, .

, , . , count , , . . , , ( , . ). , , L1, , , . , ; , .

Windows, , Win32. ( Intel Threaded Building Blocks).

    concurrency::parallel_invoke(
        [=] { poop(nullptr); },
        [=] { poop(nullptr); }
    );

PPL , , .

, .

+3

All Articles