Question

I've been doing pretty basic stuff with std::thread without any particular reason, simply in order to learn it. I thought that the simple example I created, where few threads are operating on the same data, locking each other before doing so, worked just fine, until I realized that every time I run it the returned value is different, while very close to each other, I am pretty sure they should equal each other. Some of the values I have received:

  • 21.692524
  • 21.699258
  • 21.678871
  • 21.705947
  • 21.685744

Am I doing something wrong or maybe there is underlying reason for that behaviour?

#include <string>
#include <iostream>
#include <thread>
#include <math.h>
#include <time.h>
#include <windows.h>
#include <mutex>

using namespace std;

mutex mtx;
mutex mtx2;

int currentValue = 1;
double suma = 0;

int assignPart() {
    mtx.lock();
    int localValue = currentValue;
    currentValue+=10000000;
    mtx.unlock();
    return localValue;
}

void calculatePart()
{
    int value;
    double sumaLokalna = 0;
    while(currentValue<1500000000){
        value = assignPart();
        for(double i=value;i<(value+10000000);i++){
            sumaLokalna = sumaLokalna + (1/(i));
        }
        mtx2.lock();
        suma+=sumaLokalna;
        mtx2.unlock();
        sumaLokalna = 0;
    }
}

int main()
{
    clock_t startTime = clock();
    // Constructs the new thread and runs it. Does not block execution.
    thread watek(calculatePart);
    thread watek2(calculatePart);
    thread watek3(calculatePart);
    thread watek4(calculatePart);

    while(currentValue<1500000000){
        Sleep(100);
        printf("%-12d %-12lf \n",currentValue, suma);
    }
    watek.join();
    watek2.join();
    watek3.join();
    watek4.join();
    cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
    //Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
}
Was it helpful?

Solution

Your loop

while(currentValue<1500000000){
    Sleep(100);
    printf("%-12d %-12lf \n",currentValue, suma);
}

is printing intermediate results, but you're not printing the final result.

To print the final result, add the line

    printf("%-12d %-12lf \n",currentValue, suma);

after joining the threads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top