C++多线程编程回顾(1)(C11)

1、线程join&detach,代码示例如下(实测,可用):

#include <iostream>
#include <thread>
#include <windows.h>//打印线程号所引,仅限Windows平台
using namespace std;

void Do(int num, const char* c) {
    cout << "num: " << num << "c: " << c << endl;
}

void main() {
    const int nThread = 10;
    thread thThread[nThread];

    for (int i = 0; i < nThread; i++) {
        /*创建线程 ,其中后面的Do为线程要执行的函数,再后面的两个实参为该函数传递的参数*/
        thThread[i] = thread(&Do,i,"hello");
        //打印当前线程号
        cout << "The thread id is: " << GetCurrentThreadId() << endl;
    }

    /*将新创建的所有线程join*/
    /*其作用:可以让join的线程先执行,主线程(主进程)等待join的线程执行完毕再继续执行*/
    for (auto &t : thThread)
        t.join();
        /*此处的除了使用join(),还可以使用detach()*/
        /*作用:将detach的线程交给系统管理,系统保证detach的线程的执行*/
        /*它并不像join能保线程执行完毕,也就是说主线程执行完毕*/

    return;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值