[英]What happens when a thread is constructed, and how is the thread executed
我對多線程完全陌生,並且在理解多線程的實際工作原理方面遇到了一些麻煩。
讓我們考慮以下代碼示例。 該程序只是將文件名作為輸入並計算其中的小寫字母數。
#include <iostream>
#include <thread>
#include <mutex>
#include <memory>
#include <vector>
#include <string>
#include <fstream>
#include <ctype.h>
class LowercaseCounter{
public:
LowercaseCounter() :
total_count(0)
{}
void count_lowercase_letters(const std::string& filename)
{
int count = 0;
std::ifstream fin(filename);
char a;
while (fin >> a)
{
if (islower(a))
{
std::lock_guard<std::mutex> guard(m);
++total_count;
}
}
}
void print_num() const
{
std::lock_guard<std::mutex> guard(m);
std::cout << total_count << std::endl;
}
private:
int total_count;
mutable std::mutex m;
};
int main(){
std::vector<std::unique_ptr<std::thread>> threads;
LowercaseCounter counter;
std::string line;
while (std::cin >> line)
{
if (line == "exit")
break;
else if (line == "print")
counter.print_num(); //I think that this should print 0 every time it's called.
else
threads.emplace_back(new std::thread(&LowercaseCounter::count_lowercase_letters, counter, line));
}
for (auto& thread : threads)
thread->join();
}
首先,我認為counter.print_num()
的輸出將打印 0,只要線程尚未“加入”以執行函數。 然而,程序運行正常, counter.print_num()
的輸出不為0。於是我問了自己以下問題。
構造線程時實際發生了什么?
如果上面的程序運行正常,那么線程必須在創建時執行,那么std::thread::join
方法是做什么的?
如果線程是在創建時執行的,那么在這個例子中使用多線程有什么意義呢?
提前致謝。
正如您所說,在 C++ 中,線程在創建時執行,所有std::thread::join
所做的就是等待線程完成執行。
在您的代碼中,所有線程將在循環中同時開始執行,然后主線程將等待每個線程在下一個循環中完成執行。
您似乎認為程序一次只能運行一個線程,並且它需要中斷正在執行的任何操作才能執行線程的代碼。 事實並非如此。
您可以將線程視為一個完全獨立的程序,它恰好與創建它的程序共享內存和資源。 您作為參數傳遞的函數是該程序針對每個意圖和目的的“main()”。 在 Linux 中,線程實際上是獨立的進程,但就 C++ 而言,這只是一個實現細節。
因此,在具有搶占式多任務處理的現代操作系統中,就像多個程序可以同時運行一樣,線程也可以同時運行。 請注意,我說的是can ,由編譯器和操作系統決定何時為每個線程提供 CPU 時間。
那么 std::thread::join 方法有什么作用呢?
它只是等待線程完成。
那么如果我沒有為每個線程調用 join() 方法會發生什么
它會在到達main()
結束時崩潰,因為嘗試在不加入非分離線程的情況下退出程序被視為錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.