c++11 创建一个线程

步骤:

  • a) 包含头文件
  • b) 自定义线程执行函数
  • c) 创建子线程thread thread1(thread_fun); 子线程需要完成的任务在thread_fun写
  • d) join() :汇合,阻塞主线程并等待子线程执行完,继续往下执行主线程

整个进程执行的完毕结束的标志是主线程结束; 此时,如果其他子线程还没有执行完毕,那么子线程也会被操作系统强行终止,系统抛出异常;良好的程序应该是主线程等待子线程执行完毕后,自己才能退出;

#include <thread>
#include <iostream>

using namespace std;
void thread_fun()
{
    cout << "sub thread begin,thread ID: " << this_thread::get_id() << endl;
    for (int i = 0; i < 10; i++) {
        cout << "i=" << i << endl;
        this_thread::sleep_for(chrono::seconds(1)); // 1000ms
    }
    cout << "sub thread main is over,thread ID:" << this_thread::get_id()
         << endl;
}
int main(int argc, char *argv[])
{
    cout << "main thread begin,thread ID: " << this_thread::get_id() << endl;
    //线程创建启动
    thread thread1(thread_fun);

    //阻塞等待子线程退出
    thread1.join();
    cout << "main thread is over,thread ID: " << this_thread::get_id() << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值