线程执行的顺序是什么?
What is the sequence of thread execution?
所以我最近一直试图把我的头围绕多线程和理解它是如何工作的。我这里有一些示例代码,但我不明白为什么输出是这样的。
示例代码:
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
std::mutex mtx;
int global_counter = 0;
std::mutex counter_mutex;
void five_thread_fn(){
for(int i = 0; i<5; i++){
counter_mutex.lock();
global_counter++;
std::cout << "Updated from five_thread" << endl;
counter_mutex.unlock();
// std::this_thread::sleep_for(std::chrono::seconds(5));
}
//When this thread finishes we wait for it to join
}
void ten_thread_fn(){
for(int i = 0; i<10; i++){
counter_mutex.lock();
global_counter++;
std::cout << "Updated from ten_thread" << endl;
counter_mutex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
//When this thread finishes we wait for it to join
}
int main(int argc, char *argv[]) {
std::cout << "starting thread ten..." << std::endl;
std::thread ten_thread(ten_thread_fn);
std::cout << "Starting thread five..." << endl;
std::thread five_thread(five_thread_fn);
five_thread.join();
std::cout << "Five Thread is done." << std::endl;
ten_thread.join();
std::cout << "Ten Thread is done." << std::endl;
// std::cin.ignore();
return 0;
}
我已经注释掉了线程中的时间延迟,下面是我的输出:
Starting thread ten...
Starting thread five...
Updated from five_thread
Updated from ten_thread
Updated from five_thread
Updated from five_thread
Updated from five_thread
Updated from five_thread
Five Thread is done.
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Updated from ten_thread
Ten Thread is done.
现在我想知道为什么"从ten_thread更新"出现在"从five_thread更新"的第一行之后?
在main函数中执行
时five_thread.join();
不挂起主线程,直到five_thread完成它的执行?
根据我的理解,只有在five_thread完成之后,five_thread.join()之后的行才执行(顺序)。那么ten_thread是如何被调用的呢?
main()中的代码行执行是不是顺序的?
不挂起主线程,直到five_thread完成它的执行?
是的。但是A在等待B的事实并不妨碍C在自己的时间做自己的事情。就执行而言,连接一个线程并没有赋予该线程优先级。这并不意味着正在连接的线程将在该点开始。
Concurrent execution表示并发执行。除非你显式地给出一个顺序,否则并发事件的执行之间是没有顺序的。加入线程只声明当前线程将在给定线程完成后恢复。
根据我的理解,只有在five_thread完成之后five_thread.join()之后的行执行(顺序执行)。那是怎么回事?在两者之间调用ten_thread ?
因为这个线程已经启动了。
std::thread ten_thread(ten_thread_fn);
启动执行线程。ten_thread()
没有被称为任何东西的"中间"。它是一个独立的执行线程,与所有其他线程并发执行。
线程在std::thread
实例化时启动,并在主线程运行时继续执行。
所有join()
所做的是暂停主执行线程,直到给定的执行线程终止。该执行线程已经并发运行。
只要ten_thread
被实例化,就意味着ten_thread_fn()
正在执行。
- 计算 I+V[i++] 的顺序是什么?
- C++:使用方法调用析构函数的顺序是什么?
- C++部分概念 id:显式模板规范顺序/第一个参数的特殊状态的原因是什么?
- 函数模板实例化、替换和重载解析的顺序是什么?
- 在 OpenGL 中计算矩阵时,转换的正确顺序是什么?
- 在 C++ 中,以相反顺序排序的最快方法是什么?
- 正确的包含顺序是什么
- 抛出多个异常时,catch 块执行的顺序是什么,为什么?
- 当某些错误可以接受时,顺序加载存储原子的内存顺序应该是什么
- 获取释放内存顺序与顺序一致性不同的实际示例是什么?
- 编译器在遇到提取或插入运算符时处理信息(字符串、操纵器等)的顺序是什么?
- 按特定顺序扩展可变参数模板值的最有效方法是什么?
- 在C++中为临时库调用析构函数的顺序是什么
- 操作员优先c |进行计算的确切顺序是什么
- 在虚拟继承中构造函数调用的顺序是什么
- 函数参数的销毁顺序是什么
- 函数参数的销毁顺序是什么
- 通过构造函数初始化集初始化的变量的销毁顺序是什么
- 基类的销毁顺序是什么
- openGL:使用glm进行转换的顺序是什么