多线程

参考: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;
}

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