瞎搞系列-C++11 多线程编程

C++11 多线程编程

简单多线程编程例子

关键字:

thread:建立一个线程,thread name(thread_func)

join: 加入线程队列,name.join()

#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;
void thread01(){
    for(int i=0;i<5;i++){
        std::cout<<"Thread 01 is working"<<std::endl;
        Sleep(100);
    }
}
void thread02(){
    for(int i=0;i<5;i++){
        std::cout<<"Thread 02 is working"<<std::endl;
        Sleep(200);
    }
}
int int main(int argc, char const *argv[])
{
    thread task01(thread01);
    thread task02(thread02);
    task01.join();
    task02.join();
    for(int i=0;i<5;i++){
        std::cout<<"main thread is working"<<std::endl;
    }
    return 0;
}

子线程剥离主线程

两个子线程并行执行,join函数会阻塞主流程,所以子线程都执行完成之后才继续执行主线程。可以使用detach将子线程从主流程中分离,独立运行,不会阻塞主线程

#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;
void thread01(){
    for(int i=0;i<5;i++){
        std::cout<<"Thread 01 is working"<<std::endl;
        Sleep(100);
    }
}
void thread02(){
    for(int i=0;i<5;i++){
        std::cout<<"Thread 02 is working"<<std::endl;
        Sleep(200);
    }
}
int int main(int argc, char const *argv[])
{
    thread task01(thread01);
    thread task02(thread02);
    task01.detach();
    task02.detach();
    for(int i=0;i<5;i++){
        std::cout<<"main thread is working"<<std::endl;
    }
    return 0;
}

带参子线程

在绑定的时候也可以传入参数

#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;
void thread01(int num){
    for(int i=0;i<num;i++){
        std::cout<<"Thread 01 is working"<<std::endl;
        Sleep(100);
    }
}
void thread02(int num){
    for(int i=0;i<num;i++){
        std::cout<<"Thread 02 is working"<<std::endl;
        Sleep(200);
    }
}
int int main(int argc, char const *argv[])
{
    thread task01(thread01,5);
    thread task02(thread02),5;
    task01.detach();
    task02.detach();
    for(int i=0;i<5;i++){
        std::cout<<"main thread is working"<<std::endl;
    }
    return 0;
}

mutex并行

#include <iostream>
#include <thread>
#include <Windows.h>
#include <mutex>
mutex mu;
int totalNum = 100;
void thread01(){
    while(totalNum>0){
        mu.lock();
        std::cout<<totalNum<<std::endl;
        totalNum--;
        Sleep(100);
        mu.unlock();
    }
}
void thread02(){
    whiel(totalNum>0){
        mu.lock();
        std::cout<<totalNum<<std::endl;
        totalNum--;
        Sleep(100);
        mu.unlock();
    }
}
int int main(int argc, char const *argv[])
{
    thread task01(thread01);
    thread task02(thread02);
    task01.detach();
    task02.detach();
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值