【发布时间】:2021-07-17 22:11:11
【问题描述】:
我对多线程完全陌生,在理解多线程的实际工作原理方面有点困难。
让我们考虑以下代码示例。该程序只是将文件名作为输入并计算其中的小写字母数量。
#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方法是做什么的?
如果线程是在创建的时候执行的,那么在这个例子中使用多线程有什么意义呢?
提前致谢。
【问题讨论】:
-
听起来你觉得线程更像协程。线程开始在创建时执行,
join()一直等到线程结束。除此之外,它与所有其他线程并行运行,可能在不同的 CPU 内核上。 -
@Frank 如果线程有一个指定的 start 时间(在构造时),那么我想它应该有一个指定的 end 时间。
join()等待线程结束是什么意思? -
线程在其入口点函数返回后简单地结束,就像程序在到达
main()的末尾时结束一样。 -
@Frank 那么如果我不为每个线程调用
join()方法会发生什么。
标签: c++ multithreading