My mistake is probably very obvious, but I cannot seem to figure it out... When running this, the Add and Subtract functions generate the same value when initiating new threads. If I am declaring a new variable everytime the function is called, why am i unable to generate different values at each invocation?
I have the following code,
#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;
}