1、创建线程
eg : 把函数 vooid first ( int a) ; 加入线程myThread
std : : thread myThread ( first) ;
myThread. join ( ) ;
class Hello {
public :
Hello ( ) {
std : : thread t ( std: : bind ( & Hello: : Entry, this , "World" ) ) ;
t. join ( ) ;
}
private :
void Entry ( const char* what) {
std : : this_thread: : sleep_for ( std: : chrono: : seconds ( 1 ) ) ;
std : : cout << "Hello, " << what << "!" << std: : endl;
}
} ;
std : : thread ( thread_fun, 1 ) . detach ( ) ;
2、join与detach方式
detach方式,启动的线程自主在后台运行,当前的代码继续往下执行,不等待新线程结束。
join方式,等待启动的线程完成,才会继续往下执行。
eg :
#include < iostream>
#include < thread>
using namespace std;
void thread_1 ( )
{
while ( 1 )
{
cout<< "子线程1" << endl;
}
}
void thread_2 ( int x )
{
while ( 1 )
{
cout<< "子线程2" << endl;
}
}
int main ( )
{
thread first ( thread_1) ;
thread second ( thread_2, 100 ) ;
first. join ( ) ;
second. join ( ) ;
while ( 1 )
{
std : : cout << "主线程\n" ;
}
return 0 ;
}
#include < iostream>
#include < thread>
using namespace std;
void thread_1 ( )
{
while ( 1 )
{
cout<< "子线程1111" << endl;
}
}
void thread_2 ( int x )
{
while ( 1 )
{
cout<< "子线程2222" << endl;
}
}
int main ( )
{
thread first ( thread_1) ;
thread second ( thread_2, 100 ) ;
first. detach ( ) ;
second. detach ( ) ;
for ( int i = 0 ; i < 10 ; i++ )
{
std : : cout << "主线程\n" ;
}
return 0 ;
}
但是第两个运行出的结果让我有点疑惑
1、第一个join运行的时候是一会输出"线程1"一会输出线程2;
2、但第二个detach运行的时候是先输出的主线程,按理说不是应该至少先输出几个"线程1""线程2" 再输出主线程吗?
3、是有时候还没有输出换行,比如线程1线程2然后来了一个空白行,这里盲猜是两个线程同时进行,endl还没来及的输出的时候线程2的“线程2”已经输出了导致的,稍后验证一下。
3、this_thread
有四个功能函数
1、get_id
2、yield
3、sleep_for
4、sleep_until
1、get_id std::this_thread::get_id() 获取线程id
eg :
void func ( )
{
cout << "子线程: " << this_thread: : get_id ( ) << endl;
}
int main ( )
{
cout << "主线程: " << this_thread: : get_id ( ) << endl;
thread t ( func) ;
t. join ( ) ;
}
2、yield std::this_thread::yield() 放弃线程执行,回到就绪状态
//补充c++多线程中的状态
void func ( )
{
for ( int i = 0 ; i < 100000000000 ; ++ i)
{
cout << "子线程: " << this_thread: : get_id ( ) << ", i = " << i << endl;
this_thread : : yield ( ) ;
}
}
3、sleep_for std::this_thread::sleep_for(std::chrono::seconds(n)); 暂停n秒
eg :
void func ( )
{
for ( int i = 0 ; i < 10 ; ++ i)
{
this_thread : : sleep_for ( chrono: : seconds ( 1 ) ) ;
cout << "子线程: " << this_thread: : get_id ( ) << ", i = " << i << endl;
}
}
4、sleep_until()
sleep_until():指定线程阻塞到某一个指定的时间点 time_point类型,之后解除阻塞
sleep_for():指定线程阻塞一定的时间长度 duration 类型,之后解除阻塞
eg :
void func ( )
{
for ( int i = 0 ; i < 10 ; ++ i)
{
auto now = chrono: : system_clock: : now ( ) ;
chrono : : seconds sec ( 2 ) ;
this_thread : : sleep_until ( now + sec) ;
cout << "子线程: " << this_thread: : get_id ( ) << ", i = " << i << endl;
}
}