简体   繁体   中英

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. 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.

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?

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.

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. In Linux, threads are literally separate processes, but as far as C++ is concerned, that's just an implementation detail.

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.

then what does std::thread::join method do?

It just waits until the thread is done.

So what would happen if I didn't call join() method for each one of threads

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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