gpt4 book ai didi

c++ - 为什么线程似乎随机执行?

转载 作者:行者123 更新时间:2023-12-01 15:10:51 27 4
gpt4 key购买 nike

我在理解c++线程时遇到了麻烦。
说我有以下代码,

#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;
}

如果要监视输出,则可以看到未按调用顺序访问线程。
总的来说,有一个for循环遍历从0到9的线程,但是为什么线程以不同的顺序打印(2,1,0,3,6 ... etc)。
我想念什么?

最佳答案

您什么都不会错过。创建std::thread会告诉操作系统创建一个线程,然后该线程将以任意顺序执行(无论操作系统何时运行它)。由于大多数OS调度程序都是不确定的,因此预期的行为基本上是随机的。您所看到的是预期的行为。

例如,请参见 std::thread::thread 的底部。

关于c++ - 为什么线程似乎随机执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60629414/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com