【C++】std::thread的英文资料整理

2023年9月10日,周日上午

这篇博客是我对网上的英文资料的整理和翻译


英文资料来自:

c++ - What exactly is an std::thread? - Stack Overflow


When you create a std::thread (assuming you don't use the default constructor), the constructor will use the operating system API to create a native thread, and calls the passed function.

当你创建一个std::thread类的对象,这个类的构造函数会使用操作系统的API去创建一个原生的线程,并调用你传递进来的函数。

std::thread represents a thread, managed by the operating system. It has its stack, registers, instruction pointer etc. However, it is still managed by the OS. The operating system handles all the scheduling, assigning the thread to the hardware core and then preempting it if necessary to do another work on that core.

std::thread类代表一个被操作系统管理的线程。这个线程有自己的栈、寄存器、指令指针等等。操作系统掌握所有的线程调度,能够把线程分配给CPU的核心,还可以在其他任务需要CPU的核心时停止线程。

If you launch more threads than there are cores on your CPU, and they all run all the time, the OS will start swapping them in and out, effectively keeping them all running. However, this swapping is not for free, and you can slow everything down if you have too many of them.

如果你启动的线程数比CPU的核心数要多,并且这些线程会一直运行,那么操作系统会开始交替执行这些线程,以确保这些线程能有效地”同时“运行。但是,交替运行是有代价的,如果你有太多的线程,那么你会让一切事情变慢。

However, if your threads are halted for whatever reason -- for example, you threads stop on a mutex, wait on a condition variable, or simply goes to sleep (e.g. via std::this_thread::sleep_for), then it no longer consume the hardware resources during that wait.

如果你的线程因为某些原因休眠了,那么这个线程在休眠期间不会再消耗任何硬件资源。

The operating system has a subsystem called "process scheduler" which allocates the time of the hardware CPU cores (or logical core in case of hyper threading, which I assume is what you mean by "hardware thread") time for each of the threads running on the system. The number of (logical) cores the CPUs of the system has affects how many threads can be executed in parallel, but doesn't limit how many threads the operating system can manage.

As such, nothing in particular will happen or will stop happening. If your system has more threads ready to run than number of (logical) CPU cores, then the operating system will not be able to give CPU time to all of the threads in parallel.

Note that creating native threads has a performance penalty, and having more threads waiting to run (excluding those waiting for disk or network) than the number of cores to execute them will reduce the performance of the system.

操作系统有一个负责进程调度的子系统,这个子系统会分配CPU的核心的时间给每一个运行在操作系统上的线程。CPU的核心数决定能有多少线程可以并行,但不会限制能有多少线程并发。

即使准备运行的线程数比CPU的核心数要多,也不会有什么事情发生或停止运行,只是操作系统会没有足够的CPU时间来进行并发。

需要注意的是创建原生线程有性能上的损耗。因为等着被执行的线程要比CPU的核心数多时会降低系统的性能。

你可能感兴趣的:(#,C++多线程,c++,开发语言)