简体   繁体   English

构造线程时会发生什么,以及线程是如何执行的

[英]What happens when a thread is constructed, and how is the thread executed

I'm completely new to multithreading and have a little trouble understanding how multithreading actually works.我对多线程完全陌生,并且在理解多线程的实际工作原理方面遇到了一些麻烦。

Let's consider the following example of code.让我们考虑以下代码示例。 The program simply takes file names as input and counts the number of lowercase letters in them.该程序只是将文件名作为输入并计算其中的小写字母数。

#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();
}

Firstly I though that the output of counter.print_num() will print 0 as far as the threads are not 'joined' yet to execute the functions.首先,我认为counter.print_num()的输出将打印 0,只要线程尚未“加入”以执行函数。 However, It turns out that the program works correctly and the output of counter.print_num() is not 0. So I asked myself the following questions.然而,程序运行正常, counter.print_num()的输出不为0。于是我问了自己以下问题。

What actually happens when a thread is constructed?构造线程时实际发生了什么?

If the program above works fine, then thread must be executed when is created, then what does std::thread::join method do?如果上面的程序运行正常,那么线程必须在创建时执行,那么std::thread::join方法是做什么的?

If the thread is executed at the time of creation, then what's the point of using multithreading in this example?如果线程是在创建时执行的,那么在这个例子中使用多线程有什么意义呢?

Thanks in advance.提前致谢。

As you said, in c++ the thread is executed when it is created all std::thread::join does is wait for the thread to finish execution.正如您所说,在 C++ 中,线程在创建时执行,所有std::thread::join所做的就是等待线程完成执行。

In your code all the threads will start executing simultaneously in the loop and then the main thread will wait for each thread to finish execution in the next loop.在您的代码中,所有线程将在循环中同时开始执行,然后主线程将等待每个线程在下一个循环中完成执行。

You seem to be under the impression that the program can only be running one thread at a time, and that it needs to interrupt whatever it's doing in order to execute the code of the thread.您似乎认为程序一次只能运行一个线程,并且它需要中断正在执行的任何操作才能执行线程的代码。 That's not the case.事实并非如此。

You can think of a thread as a completely separate program that happens to share memory and resources with the program that created it.您可以将线程视为一个完全独立的程序,它恰好与创建它的程序共享内存和资源。 The function you pass as an argument is that program's 'main()` for every intent and purpose.您作为参数传递的函数是该程序针对每个意图和目的的“main()”。 In Linux, threads are literally separate processes, but as far as C++ is concerned, that's just an implementation detail.在 Linux 中,线程实际上是独立的进程,但就 C++ 而言,这只是一个实现细节。

So, in a modern operating system with preemptive multitasking, much like multiple programs can run at the same time, threads can also run at the same time.因此,在具有抢占式多任务处理的现代操作系统中,就像多个程序可以同时运行一样,线程也可以同时运行。 Note that I say can , it's up to the compiler and OS to decide when to give CPU time to each thread.请注意,我说的是can ,由编译器和操作系统决定何时为每个线程提供 CPU 时间。

then what does std::thread::join method do?那么 std::thread::join 方法有什么作用呢?

It just waits until the thread is done.它只是等待线程完成。

So what would happen if I didn't call join() method for each one of threads那么如果我没有为每个线程调用 join() 方法会发生什么

It would crash upon reaching the end of main() because attempting to exit the program without joining a non-detached thread is considered an error.它会在到达main()结束时崩溃,因为尝试在不加入非分离线程的情况下退出程序被视为错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM