所以我最近一直試圖圍繞多線程來了解它是如何工作的。我在這裏有一些示例代碼,但我不明白爲什麼輸出是這樣的。線程執行的順序是什麼?
示例代碼:
#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()中的代碼行是不是順序執行?
'ten_thread'不是主線程。該程序中有** 3 **線程,唯一被等待的線程是主線程。 'five_thread'和'ten_thread'同時運行。 – Galik