• 欢迎光临~

并发多进程4

开发技术 开发技术 2022-08-30 次浏览

第四节 创建多个线程、数据共享问题分析、案例代码

一、创建和等待多个线程

#include <thread>
#include <iostream>
#include <vector>

using namespace std;
void TextThread()
{
    cout << "我是线程" << this_thread::get_id() << endl;
    /**/
    cout << "线程" << this_thread::get_id() << "执行结束" << endl;
}
int main()
{
    vector<thread> threadagg;
    for (int i = 0; i < 10; ++i)
    {
        threadagg.push_back(thread(TextThread));
    }
    for (int i = 0; i < 10; ++i)
    {
        threadagg[i].join();
    }
}

把thread对象放入到容器中管理,看起来像个thread对象数组,对一次创建大量的线程并对大量线程进行管理有好处
多个线程执行顺序是乱的,跟操作系统内部对线程的运行调度机制有关
二:数据共享问题分析
2.1 只读的数据

是安全稳定的
2.2 有读有写

若不加处理,就会出错
最简单的防止崩溃方法:读的时候不能写,写的时候不能读。
写的动作分10小步,由于任务切换,导致各种诡异的事情发生(最可能的还是崩溃)


原文链接:https://blog.csdn.net/qq_38231713/article/details/106091759

程序员灯塔
转载请注明原文链接:并发多进程4
喜欢 (0)