该代码涉及到多线程的使用,其创建了两个子线程,让两个子线程同时并发工作,从结果中感受到了两个程序可以同时进行,总结一下C+多线程该代码使用到的相关知识代码:
#include
thread th(子线程函数);
th.join() 子线程回收;
this_thread::get_id() 获取子线程ID;
this_thread::sleep_for(1000ms) 1s子程序休眠,暂时释放cpu资源,用于以后的多个子线程时间上同步或者调度。
// pthread.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <thread>
using namespace std;
void ThreadMain1() { //子线程
cout << "1:thread was begin!!,son's id :" <<this_thread::get_id()<< endl;
for (int i = 0; i < 10; i++) {
cout << "thread_1 : ";
cout << i << endl;
this_thread::sleep_for(1000ms);
}
}
void ThreadMain2() { //子线程
cout << "2:thread was begin!!,son's id :" << this_thread::get_id() << endl;
for (int i = 0; i < 10; i++) {
cout << "thread_2 :" ;
cout << i << endl;
this_thread::sleep_for(1000ms);
}
}
int main()
{
cout << " I am father,my ID:" <<this_thread::get_id()<<endl;
//子线程id &&//子线程创建
thread th1(ThreadMain1); // 子线程在c11(thread) 作为一个对象,初始化,示例名称为th ,类名称 thread
thread th2(ThreadMain1);
th1.join(); //调用方法回收子线程资源(子线程做完就回收)
th2.join();
//子线程释
return 0;
}
结果: