2016-08-28 177 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