c++多线程技术入门
thread
thread 即 进程,它可以同时执行多个任务,其一大特点是共享内存 ex:
设全局变量 a = 1 ; int main() { a++;thread t1; thread t2;}最终输出结果应该为3 ;
#include < iostream >
#include < thread >
using namespace std;
void fun( );
int a = 1//全局变量1;
int main()
{
thread t ( fun ) ;// 线程1
thread t1 ( fun ) ;// 线程2
if(t.joinable() && t1.joinable() )
{
t.join();
t1.join();
}
}
void fun( )
{
a++;
cout << a << endl ;
}
thread运行速度并不相同
线程1 运行1++至50与 线程2运行1++至50并不是同时运行。
#include < thread >
#include < iostream >
using namespace std ;
void fun( );
int main()
{
thread t ( fun ) ;
thread t1( fun ) ;
if( t.joinable() && t1.joinable() )
{
t.join();
t1.join();
}
}
void fun( )
{
int a;
for (a = 1; a <= 50; a++)
{
cout << a << endl ;
}
}
很明显从图中可以观察出线程1运行至17 开始与线程2一起进行,线程2开始继续往后运行。