C++线程 基础教程

#include <iostream>
#include <thread>
using namespace std;

void call(int tid)
{
    cout << "Launched by thread " << tid << endl;
}

int main()
{
    thread t[10];//启动一组线程
    for(int i=0;i<10;i++)
    {
        t[i]=thread(call,i);
    }
    for(int i=0;i<10;i++)
    {
        t[i].join();
    }

    return 0;
}

这里写图片描述

能看到上面的结果中,程序一旦创建一条线程,其运行存在顺序不确定的现象。程序员的任务就是要确保这组线程在访问公共数据时不要出现阻塞。最后几行,所显示的错乱输出,甚至是会输出些混乱的字符。原因在于,程序内的11条线程都在竞争性地使用stdout这个公共资源,要避免上面的问题,可以在代码中使用拦截器(barriers),如std:mutex,以同步(synchronize)的方式来使得一群线程访问公共资源,或者,如果可行的话,为线程们预留下私用的数据结构,避免使用公共资源。

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

std::mutex m;
void call(int tid)
{
    m.lock();
    cout << "Launched by thread " << tid << endl;
    m.unlock();
}
int main()
{
    thread t[10];//启动一组线程
    for(int i=0;i<10;i++)
    {
        t[i]=thread(call,i);
    }
    for(int i=0;i<10;i++)
    {
        t[i].join();
    }

    return 0;
}

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值