【发布时间】:2020-06-23 21:55:18
【问题描述】:
我的错误可能很明显,但我似乎无法弄清楚...... 运行它时,Add 和 Subtract 函数在启动新线程时生成相同的值。如果我每次调用函数时都声明一个新变量,为什么我无法在每次调用时生成不同的值?
我有以下代码,
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <numeric>
#include <cmath>
#include <sstream>
#include <thread>
#include <chrono>
#include <ctime>
#include <mutex>
int GetRandom(int max){
//generate a pseudo-random number with time as the seed
//time as seed will always return a different starting point
srand(time(NULL));
//mod max to ensure we return a number below max
return rand() % max;
}
std::string GetTime(){
auto nowTime = std::chrono::system_clock::now();
std::time_t sleepTime =
std::chrono::system_clock::to_time_t(nowTime);
return std::ctime(&sleepTime);
}
double acctBalance = 10;
// Protects shared data from being accessed at the
// same time
std::mutex acctLock;
void Add(int id,
double adding, int sleep){
int rand = GetRandom(10);
std::cout <<"Add: "<<rand<< "\n";
}
// acctLock.unlock();
void Subtract(int id, double subtract, int sleep){
int rand = GetRandom(10);
std::cout <<"Subtract: "<<rand<< "\n";
// acctLock.unlock();
}
int main()
{
int rand = 3;
int count = 10;
std::vector<std::thread> threads;
threads.reserve(count);
for (size_t i = 0; i < count; i=i+2)
{
threads.emplace_back(Add, i, 15,rand);
threads.emplace_back(Subtract, i+1, 15,rand);
}
for (auto& thread : threads)
{
thread.join();
}
return 0;
}
【问题讨论】:
-
srand(time(NULL));由于这些功能(实际上)同时发生,因此您正在为 PRNG 播种相同的值。 -
srand()不属于任何地方,而是曾经的地方,通常在main的最前面。而且您无论如何都不应该使用它;请改用<random>。它、线程和可变参数模板是近十年前添加到语言库中的前三名令人敬畏和纯粹的赢家。 -
我已经 left a comment 在您之前关于此代码的问题中警告您此问题。
srand()— why call it only once? -
好吧,实际上你永远不应该在 C++ 中使用 srand,问题很多。现在的分布不那么明显了,但就是这样。
标签: c++ multithreading