C++温故补缺(十五):多线程

多线程

参考:CSDN,知乎

传统C++(C++11之前)中并没有引入线程的概念,如果想要在C++中实现多线程,需要借助操作系统平台提供的API,如Linux的<pthread.h>,或windows下的<windows.h>

从C++11开始提供了语言层面的多线程,包含在头文件<thread>中,它解决了跨平台的问题,并提供了管理线程,保护共享数据,线程间同步操作,原子操作等类。

何时使用并发?

程序使用并发的原因有两种。一是为了关注点分离;程序中需要执行不同的功能,就使用不同的线程来执行。二是为了提高性能,同时处理多个任务或者充分利用cpu资源,节省时间。

创建线程

创建线程用到thread类,用它来创建对象,其必须的参数是一个函数

#include<thread>
void fun(){}
thread th1(fun);

启用线程有两种方式,join和detach。join会阻塞父线程,等待子线程执行完,父线程才结束。而detach不会等待,一旦父线程执行完,未执行完的子线程被释放掉。

例子:

#include<iostream>
#include<thread>
#include<unistd.h>
using namespace std;
void func(){
    for(int i=0;i<3;i++){
        cout<<"func"<<endl;
        sleep(1);
    }
}

int main(){
    thread th1(func);
    th1.join();
    cout<<"main"<<endl;
    return 0;
}

join模式下,子现场把func()函数执行完,main线程才结束

修改成detach模式:

int main(){
    thread th1(func);
    th1.detach();
    cout<<"main"<<endl;
    return 0;
}

多线程

采用多线程和单线程执行两个函数对比

#include<iostream>
#include<thread>
#include<unistd.h>
#include<time.h>
using namespace std;
void func(){
    for(int i=0;i<3;i++){
        cout<<"func"<<" ";
        sleep(1);
    }
}
void func1(){
    for(int i=0;i<3;i++){
        cout<<"func1"<<" ";
        sleep(1);
    }
}

void Main(){
    func();
    func1();
}

void Main1(){
    thread th(func);
    thread th1(func1);
    th.join();
    th1.join();
}
int main(){
    time_t start=0,end=0;
    time(&start);
    Main();
    time(&end);
    cout<<"single thread exectime:"<<difftime(end,start)<<endl;
    time(&start);
    Main1();
    time(&end);
    cout<<"multi threads exectime:"<<difftime(end,start)<<endl;
}

多线程比单线程执行时间少了一半

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值