1

I am having trouble understanding c++ threads. 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){
    srand(time(NULL));
    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 = 100;

// Protects shared data from being accessed at the
// same time
std::mutex acctLock;

void GetMoney(int id,
        double withdrawal){

    // 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(3));

    std::cout << id << 
            " tries to withdrawal $" <<
            withdrawal << " on " <<
            GetTime() << "\n";

    if((acctBalance - withdrawal) >= 0){
        acctBalance -= withdrawal;
        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()
{
    /* ----- SIMPLE THREAD EXAMPLE -----
    // Create a thread and pass a parameter
    // to the function
    std::thread th1 (ExecuteThread, 1);

    // Join the thread to the main thread
    // meaning main waits for this thread to
    // stop executing before continuing execution
    // of code in main
    th1.join();

    std::thread th2 (ExecuteThread, 2);
    th2.join();
    ----- END SIMPLE THREAD EXAMPLE ----- */

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

    for(int i = 0; i < 10; ++i){
        threads[i] = std::thread(GetMoney, i, 15);
    }

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



    return 0;
}

If I were to monitor the output, I can see that the threads are not being accessed in the order in which they are being called. In main, there is a for loop iterating through the threads from 0 to 9, but why are the threads printing in a different order(2,1,0,3,6...etc). What am i missing ?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • You are using `srand()` wrong. See https://stackoverflow.com/questions/6729214/rand-returns-same-values-when-called-within-a-single-function – Galik Mar 11 '20 at 05:49
  • Looks like you need an introduction to the equally interesting and tedious topic of "thread synchronization" :) – AlexGeorg Mar 11 '20 at 09:31
  • 1
    FWIW, a thread is not something that you can _call_. You can _create_ / _start_ a thread, and then the thread executes your code. – Solomon Slow Mar 11 '20 at 12:55
  • Because they're threads. If you want sequential execution, don't use them. – user207421 Mar 13 '20 at 00:18

1 Answers1

6

You're not missing anything. Creating an std::thread tells the OS to create a thread, which then executes in an arbitrary order (whenever the OS gets around to having it run). The expected behavior is essentially random as most OS schedulers are non-deterministic. What you are seeing is expected behavior.

As an example, see the bottom of std::thread::thread.

Travis Gockel
  • 26,877
  • 14
  • 89
  • 116