使用互斥锁正确编写的代码仍然可以挥发吗?

时间:2014-04-16 17:05:44

标签: c++ multithreading stdthread

我一直在用std :: thread做很基本的东西,没有任何特别的原因,只是为了学习它。我认为我创建的简单示例,其中几个线程在相同的数据上运行,在这样做之前互相锁定,工作得很好,直到我意识到每次运行它时返回的值都不同,而非常接近每个另外,我很确定他们应该相互平等。我收到的一些价值观:

  • 21.692524
  • 21.699258
  • 21.678871
  • 21.705947
  • 21.685744

我做错了什么或者可能存在这种行为的根本原因?

#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.
}

1 个答案:

答案 0 :(得分:2)

你的循环

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

正在打印中间结果,但您没有打印最终结果。

要打印最终结果,请添加

    printf("%-12d %-12lf \n",currentValue, suma);
加入线程后