多线程编程学习C+------------------第一课

该代码涉及到多线程的使用,其创建了两个子线程,让两个子线程同时并发工作,从结果中感受到了两个程序可以同时进行,总结一下C+多线程该代码使用到的相关知识代码:
#include
thread th(子线程函数);
th.join() 子线程回收;
this_thread::get_id() 获取子线程ID;
this_thread::sleep_for(1000ms) 1s子程序休眠,暂时释放cpu资源,用于以后的多个子线程时间上同步或者调度。

// pthread.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <thread>

using namespace std;

void ThreadMain1() { //子线程
    cout << "1:thread was begin!!,son's id :" <<this_thread::get_id()<< endl;
    for (int i = 0; i < 10; i++) {
        cout << "thread_1 : ";
        cout << i << endl;
        this_thread::sleep_for(1000ms);
    }
}
void ThreadMain2() { //子线程
    cout << "2:thread was begin!!,son's id :" << this_thread::get_id() << endl;
    for (int i = 0; i < 10; i++) {
        cout << "thread_2 :" ;
        cout << i << endl;
        this_thread::sleep_for(1000ms);
    }
}
int main()
{       
         cout << " I am father,my ID:" <<this_thread::get_id()<<endl; 
        //子线程id &&//子线程创建
        thread th1(ThreadMain1);  //  子线程在c11(thread) 作为一个对象,初始化,示例名称为th ,类名称 thread
        thread th2(ThreadMain1);
        th1.join(); //调用方法回收子线程资源(子线程做完就回收)
        th2.join();
        //子线程释
        return 0;
}

结果:在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值