基于C的多线程实例

直接上完整代码

#include <iostream>
#include "stdio.h"
#include "stdint.h"
#include <stdlib.h>

#include <windows.h>
#include <thread>

using namespace std ;

bool task1_should_run = true ;

void task1_exit(){
    task1_should_run = false ;
}

//任务1
void task1(void){  
    for (int i = 0; task1_should_run ; ++i){
        cout << "task1\n";
        Sleep(1000);
    }
    cout << "task1over \n";
}
//任务2
void task2(void){
    for (int i = 0; i < 20; ++i){
        cout << "task2\n";
        Sleep(1000);
    }
    cout << "task2over \n";
}

int main( int argc, char **argv ){

    thread thread1(task1);  //实例化一个线程对象th1,使用函数t1构造,然后该线程就开始执行了(t1())
    thread thread2(task2);  //

    Sleep(5000);
    task1_exit(); //软件自行退出
    
    // 必须将线程join或者detach 等待子线程结束主进程才可以退出,否则主线程会先退出,程序崩溃报错
    thread1.join();
    thread2.join(); 
    //or use detach
    //thread1.detach();
    
    printf("thread test\r\n");
    return 0 ;
}

测试说明

main函数开始,创建了两个线程,参数为自定义的函数(函数中可以死循环),延迟5s后手动软件退出任务1,然后等待两任务的退出,两任务均退出时,才退出主程序

注意:如果不等任务退出,就直接退出主程序,会发生软件崩溃的错误,必须手动保护

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值