0

I am trying to create a program that will add and subtract from a global variable. The add and subtract features will be handled by threads. How do I continuously add/subtract until the global variable has reached some threshold?

Say 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);
    // The exception safe way to protect access
    // to code within its scope. The lock is released
    // after execution leaves this scope
    std::lock_guard<std::mutex> lock(acctLock);

    // Blocks access between lock and unlock
    // until execution completes
    // This isn't good to use however if an error
    // occurs between lock and unlock
    // acctLock.lock();

    std::this_thread::sleep_for(std::chrono::seconds(sleep));

    std::cout << id <<
            ": adding : " <<
            rand << " on " <<
            GetTime() << ": slept for " << sleep<<"seconds"<< "\n";


    if((acctBalance - rand) <= 20){
        acctBalance += rand;
        std::cout << "New Account Balance is $" <<
                acctBalance << "\n";
    } else {
        std::cout << "Not Enough Money in Account\n";
        std::cout << "Current Balance is $" <<
                acctBalance << "\n";
    }
    // acctLock.unlock();
}

void Subtract(int id, double subtract, int sleep){
    int rand = GetRandom(10);
        // The exception safe way to protect access
    // to code within its scope. The lock is released
    // after execution leaves this scope
    std::lock_guard<std::mutex> lock(acctLock);

    // Blocks access between lock and unlock
    // until execution completes
    // This isn't good to use however if an error
    // occurs between lock and unlock
    // acctLock.lock();

    std::this_thread::sleep_for(std::chrono::seconds(sleep));

    std::cout << id <<
            " tries to withdrawal $" <<
            rand << " on " <<
            GetTime() << ": slept for " << sleep<<"seconds"<<"\n";

    if((acctBalance - rand) <=20){
        acctBalance -= rand;
        std::cout << "New Account Balance is $" <<
                acctBalance << "\n";
    } else {
        std::cout << "Not Enough Money in Account\n";
        std::cout << "Current Balance is $" <<
                acctBalance << "\n";
    }
    // acctLock.unlock();
}

int main()
{

    // We will create a pool of threads that
    // will access a bank account in no particular
    // order
    std::thread threads[2];

    int rand = 3;
    int x = 10;
      threads[0] = std::thread(Add, 0, 15,rand);
      threads[1] = std::thread(Subtract, 1, 15,rand);

      for(int i = 0; i < 2; ++i){
          threads[i].join();
      }

    return 0;
}

I currently have created 2 threads, 1 for adding, another for subtracting. But my program will only add and subtract from the global variable one time each. I figure I should create a dynamic array of threads that will grow until the acctBalance reaches some number. How would I go about accomplishing this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

2

There isn't anything complicated here, just create a vector and add threads to it:

std::vector<std::thread> threads;
threads.reserve(count);
for (size_t i = 0; i < count; i++)
{
  threads.emplace_back(Add, 0, 15,rand);
}
for (auto& thread : threads)
{
  thread.join();
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60