线程执行的顺序是什么?

What is the sequence of thread execution?

本文关键字:是什么 顺序 执行 线程      更新时间:2023-10-16

所以我最近一直试图把我的头围绕多线程和理解它是如何工作的。我这里有一些示例代码,但我不明白为什么输出是这样的。

示例代码:

#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更新"的第一行之后?

在main函数中执行

five_thread.join();

不挂起主线程,直到five_thread完成它的执行?

根据我的理解,只有在five_thread完成之后,five_thread.join()之后的行才执行(顺序)。那么ten_thread是如何被调用的呢?

main()中的代码行执行是不是顺序的?

不挂起主线程,直到five_thread完成它的执行?

是的。但是A在等待B的事实并不妨碍C在自己的时间做自己的事情。就执行而言,连接一个线程并没有赋予该线程优先级。这并不意味着正在连接的线程将在该点开始

Concurrent execution表示并发执行。除非你显式地给出一个顺序,否则并发事件的执行之间是没有顺序的。加入线程只声明当前线程将在给定线程完成后恢复。

根据我的理解,只有在five_thread完成之后five_thread.join()之后的行执行(顺序执行)。那是怎么回事?在两者之间调用ten_thread ?

因为这个线程已经启动了。

std::thread ten_thread(ten_thread_fn);

启动执行线程。ten_thread()没有被称为任何东西的"中间"。它是一个独立的执行线程,与所有其他线程并发执行。

线程在std::thread实例化时启动,并在主线程运行时继续执行。

所有join()所做的是暂停主执行线程,直到给定的执行线程终止。该执行线程已经并发运行。

只要ten_thread被实例化,就意味着ten_thread_fn()正在执行。