线程执行的顺序是什么?

时间:2016-08-28 02:03:19

标签: c++ multithreading

所以我最近一直试图绕过多线程并理解它是如何工作的。我这里有一些示例代码,但我无法理解为什么输出就是这样。

示例代码:

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

现在我想知道为什么&#34;从ten_thread更新&#34;出现在&#34;的第一行后,从five_thread&#34;?

更新

我做的主要功能

five_thread.join();

在five_thread完成执行之前,是否暂停主线程?

据我所知,只有在five_thread结束后,才会执行five_thread.join()之后的行(顺序)。那么如何调用ten_thread呢?

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

2 个答案:

答案 0 :(得分:1)

  

据我所知,只有在五线程结束后才会这样   five_thread.join()之后的行执行(顺序)。怎么样   在这之间调用ten_thread?

因为该线程已经启动。

std::thread ten_thread(ten_thread_fn);

这将启动执行线程。 ten_thread()并未被称为“介于两者之间”。它是一个独立的执行线程,与所有其他线程并发执行。

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

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

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

答案 1 :(得分:1)

  

在five_thread完成执行之前,是否暂停主线程?

是。但是A在B上等待的事实并没有以某种方式阻止C在自己的时间做自己的事情。加入线程并不会在执行方面给予该线程优先级。这并不意味着正在加入的线程将启动

并发执行意味着并发执行。除非你明确给它一个,否则执行并发事件之间没有顺序。加入一个线程只表示当前线程将在给定的线程完成后恢复。

相关问题