所以我最近一直试图围绕多线程来了解它是如何工作的。我在这里有一些示例代码,但我不明白为什么输出是这样的。线程执行的顺序是什么?
示例代码:
#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.
现在我想知道为什么“从ten_thread更新”出现后,第一行“从five_thread更新”?
在当我做
five_thread.join();
直到five_thread完成其执行这是否不挂起主线程的主要功能?
据我了解,只有在five_thread结束后,five_thread.join()才会执行(按顺序)。那么这个ten_thread是如何被调用的呢?
main()中的代码行是不是顺序执行?
'ten_thread'不是主线程。该程序中有** 3 **线程,唯一被等待的线程是主线程。 'five_thread'和'ten_thread'同时运行。 – Galik