简体   繁体   English

为什么线程似乎是随机执行的?

[英]Why do threads seem to execute randomly?

I am having trouble understanding c++ threads.我无法理解 C++ 线程。 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).在 main 中,有一个 for 循环遍历从 0 到 9 的线程,但为什么线程以不同的顺序打印(2,1,0,3,6...等)。 What am i missing ?我错过了什么?

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).创建一个std::thread告诉操作系统创建一个线程,然后以任意顺序执行(只要操作系统开始运行)。 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 .例如,请参阅std::thread::thread的底部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM