1.启动线程
(1)使用对象
“小试牛刀”中thread构造时传入的是函数,还可以传入对象。
#include <thread>
#include <iostream>
void func()
{
std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl;
std::cout<<"Hello Word"<<std::endl;
}
class MyFunc
{
public:
//重载的函数操作符,对象使用起来就像对象是一个函数一样
void operator()()//无参数无返回值
{
func();
}
};
int main()
{
std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl;
MyFunc myFunc;//需先定义类的对象
std::thread workerThread(myFunc);
workerThread.join();
return 0;
}
(2)使用参数
#include <thread>
#include <iostream>
#include <string>
void func(int i,std::string const &s)
{
std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl;
std::cout<<"Hello Word"<<" "<<s<<" "<<i<<std::endl;
}
int main()
{
std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl;
std::string str="at";
//注意这里第二个参数的写法
//为何不直接传str:虽然函数func的第二个参数期待传入一个引用,但是std::thread得构造函数
//并不知晓;构造函数无视函数期待的数据类型,并盲目的拷贝已提供的变量。当线程调用func函数
//时,传递给函数的参数是str拷贝的引用,而非数据本身的引用。使用std::ref可以解决
//这个问题,将参数转换成引用的形式。
std::thread workerThread(func,20161016,std::ref(str));
workerThread.join();
return 0;
}
(3)使用move
#include <thread>
#include <iostream>
#include <string>
void func(int i,std::string const &s)
{
std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl;
std::cout<<"Hello Word"<<" "<<s<<" "<<i<<std::endl;
}
void func_other(int i,std::string const &s)
{
std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl;
std::cout<<"C++11"<<" "<<s<<" "<<i<<std::endl;
}
int main()
{
std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl;
std::string str="at";
std::thread workerThread1(func,20161016,std::ref(str));
std::thread workerThread2=std::move(workerThread1);
workerThread1=std::thread(func_other,20161016,std::ref(str));
std::thread workerThread3;
std::thread workerThread4;
//此句崩溃,workerThread4并未启动
// workerThread4.join();
workerThread3=std::move(workerThread2);
//此句崩溃,因为workerThread1已经关联一个线程
// workerThread1=std::move(workerThread3);
workerThread1.join();
//此句崩溃,因为workerThread2没有关联一个线程
// workerThread2.join();
workerThread3.join();
return 0;
}
2.后台运行线程
#include <thread>
#include <iostream>
#include <string>
#include <chrono>
#include <assert.h>
void func(int i,std::string const &s)
{
std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl;
std::cout<<"Hello Word"<<" "<<s<<" "<<i<<std::endl;
}
int main()
{
std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl;
std::string str="at";
std::thread workerThread(func,20161016,std::ref(str));
//使用detach()会让线程在后台运行,也就是说主线程不会等待workerThread结束。如果线程detach(),
//不可能有std::thread对象能引用它,而且不能再调用该线程的join()方法。
workerThread.detach();
//workerThread.joinable()为false
assert(!workerThread.joinable());
//延时10秒,否则然函数func函数还未执行,main函数就退出了
std::this_thread::sleep_for(std::chrono::seconds(10));
return 0;
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容