2016-08-28 131 views
1

所以我最近一直试图围绕多线程来了解它是如何工作的。我在这里有一些示例代码,但我不明白为什么输出是这样的。线程执行的顺序是什么?

示例代码:

#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()中的代码行是不是顺序执行?

+0

'ten_thread'不是主线程。该程序中有** 3 **线程,唯一被等待的线程是主线程。 'five_thread'和'ten_thread'同时运行。 – Galik

回答

1

是不是挂起主线程,直到five_thread完成其执行?

是的。但是,A在等待B的事实并不能阻止C在自己的时间里做自己的事情。加入一个线程并不会为该线程赋予执行优先权。这并不意味着正在加入的线程在那时开始

并发执行手段并发执行。在执行并发的东西之间没有任何顺序,除非你明确地给它一个。加入一个线程只会声明当前线程将在给定线程完成后恢复。

+0

好了,然后“从ten_thread更新”发生,并且由于该线程有1秒的等待时间,“从five_thread更新”在1秒内连续出现非常快。因为ten_thread还没有完全停止,但它只是在等待。这意味着它仍然与five_thread同时发生。谢谢,我现在明白了。我在没有延时的情况下进行测试,并且消息以互相交替的顺序打印出来。 – Red

1

据我了解,这是只有在five_thread面漆 five_thread.join()后的行执行(按顺序)。那么 之间是如何调用ten_thread的呢?

因为该线程已经启动。

std::thread ten_thread(ten_thread_fn); 

这将启动执行线程。没有被称为“之间”的任何东西。它是一个独立的执行线程,与所有其他线程同时执行。

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

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

只要ten_thread得到实例化,这意味着ten_thread_fn()正在执行,大体上来说。

+0

我明白了,现在我明白了何时开始执行。谢谢! – Red