直接上完整代码
#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,然后等待两任务的退出,两任务均退出时,才退出主程序
注意:如果不等任务退出,就直接退出主程序,会发生软件崩溃的错误,必须手动保护