所以我最近一直在努力研究多线程并了解它是如何工作的。我这里有一些示例代码,但我不明白为什么输出是这样的。
示例代码:
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
std::mutex mtx;
int global_counter = 0;
std::mutex counter_mutex;
void five_thread_fn(){
for(int i = 0; i<5; i++){
counter_mutex.lock();
global_counter++;
std::cout << "Updated from five_thread" << endl;
counter_mutex.unlock();
// std::this_thread::sleep_for(std::chrono::seconds(5));
}
//When this thread finishes we wait for it to join
}
void ten_thread_fn(){
for(int i = 0; i<10; i++){
counter_mutex.lock();
global_counter++;
std::cout << "Updated from ten_thread" << endl;
counter_mutex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
//When this thread finishes we wait for it to join
}
int main(int argc, char *argv[]) {
std::cout << "starting thread ten..." << std::endl;
std::thread ten_thread(ten_thread_fn);
std::cout << "Starting thread five..." << endl;
std::thread five_thread(five_thread_fn);
five_thread.join();
std::cout << "Five Thread is done." << std::endl;
ten_thread.join();
std::cout << "Ten Thread is done." << std::endl;
// std::cin.ignore();
return 0;
}
我已经注释掉线程中的时间延迟,这是我的输出:
Starting thread ten...
Starting thread five...
Updated from five_thread
Updated from ten_thread
Updated from five_thread
Updated from five_thread
Updated from five_thread
Updated from five_thread
Five Thread is done.
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Ten Thread is done.
现在我想知道为什么“updated from ten_thread”出现在“updated from five_thread”的第一行之后?
在我做的main函数中
five_thread.join();
在 five_thread 完成执行之前不会挂起主线程吗?
据我了解,只有在 five_thread 完成后, five_thread.join() 之后的行才会(顺序)执行。那么中间的 ten_thread 是如何被调用的呢?
main()中代码行的执行不是顺序的吗?
最佳答案
Does that not suspend the main thread until five_thread completes its execution?
是的。但是 A 正在等待 B 的事实并不能以某种方式阻止 C 在自己的时间做自己的事情。加入一个线程并不会赋予该线程执行方面的优先级。这并不意味着正在加入的线程将在该点开始。
并发执行意味着并发执行。并发事物的执行之间没有顺序,除非您明确给它一个。加入线程仅说明当前线程将在给定线程完成后恢复。
关于c++ - 线程执行的顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187393/