繁体   English   中英

线程执行的顺序是什么?

[英]What is the sequence of thread execution?

因此,我最近一直在尝试围绕多线程进行研究并了解其工作原理。 我在这里有一些示例代码,但我不明白为什么输出是这样。

示例代码:

#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.

现在我想知道为什么在“从fives_thread更新”的第一行之后出现“从ten_thread更新”?

在我做的主要功能中

five_thread.join();

在fiver_thread完成执行之前,是否不会挂起主线程?

据我了解,仅在Five_thread完成之后,fives_thread.join()之后的行才顺序执行。 那么如何在两者之间调用ten_thread?

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

据我了解,仅在Five_thread完成之后,fives_thread.join()之后的行才顺序执行。 那么如何在两者之间调用ten_thread?

因为该线程已经启动。

std::thread ten_thread(ten_thread_fn);

这将启动执行线程。 ten_thread()不会在任何事物之间“被调用”。 它是一个独立的执行线程,与所有其他线程同时执行。

该线程在实例化std::thread时启动,并在主线程进行业务处理时继续执行。

join()所做的只是暂停主执行线程,直到给定的执行线程终止。 该执行线程已在同时运行。

实例化ten_thread ,就意味着松散地说, ten_thread_fn()正在执行。

在fiver_thread完成执行之前,是否不会挂起主线程?

是。 但是,A在等待B的事实并不能以某种方式阻止C在自己的时间上做自己的事情。 在执行方面,加入线程不会赋予该线程优先级。 这并不意味着要加入的线程将在该点开始

并发执行意味着并发执行。 并发执行之间没有顺序,除非您明确地给它一个顺序。 加入线程仅说明当前线程将在给定线程完成后恢复。

暂无
暂无

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

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