1.创建线程函数std :: thread
C++11在语言级别上提供了线程的支持,不考虑性能的情况下可以完全代替操作系统的线程库,而且使用起来非常方便,为开发程序提供了很大的便利
std :: thread 创建线程函数,使用std的thread实例化一个线程对象创建。
get_id() 取得目前的线程 id, 回传一个 std::thread::id 类型
joinable() 检查是否可 join
join() // 阻塞当前线程,等待子线程执行完毕
detach() // 与该线程分离,一旦该线程执行完后它所分配的资源就会被释放
native_handle() 取得平台原生的 native handle.
sleep_for() // 停止目前线程一段指定的时间
yield() // 暂时放弃CPU一段时间,让给其他线程
=================================
创建线程函数代码例子
include<iostream>
include<thread>
void printhelloworld(std::string msg)
{
std::cout<<"helloworld"<<std:endl;
return;
}
int main {
1.创建线程
//hellow thread作为参数传进去
std :: thread thresd1(printhelloworld,"hellow thread");
bool isjoin = thresd1.joinable();
if(isjoin){
thresd1.join(); //等待子线程结束,主线程在子线程结束后结束
}
else{
printf("error");
}
//thresd1.detach(); //主线程结束,子线程在后台运行
return 0;
}
========================================
2.线程使用中会遇到的一些传参问题
std::thread t()传入的形参1是临时变量,main函数返回后内存释放后引用变量无法访问到
void th1(int &x){
x += 1;
}
int main()
{
std::thread t(th1,1);
t.join();
return 0;
}
std::ref 传递引用类型
std::ref是C++标准库中的一个模函数,位于<functional>头文件中。它用于将一个对象包装成一个引用,以便在函数调用或者模板实例化时传递引用而不是拷贝对象。
使用std::ref可以将一个对象传递给需要引用参数的函数或者模板,从而避免对象的拷贝。这在某些情况下可以提高性能,特别是当对象较大或者拷贝构造函数较为复杂时。
#include<iostream>
#include<thread>
std::thread t;
int a = 1; //全局变量
void th1(int &x){
x += 1;
}
int main()
{
std::thread t(th1,std::ref(a));
t.join();
return 0;
}
==============================
ptr指向的地址存放整数1,但是把地址传递给t的下一刻立马被释放了,导致th1访问的地址里面的数已经不是1了。
#include<iostream>
#include<thread>
std::thread t;
void th1(int *x){
std::cout<< *x <<std::endl;//打印出3
}
int main()
{
int* ptr = new int(1);
std::thread t(th1,ptr);
delete ptr;
t.join();
return 0;
}
===============================
定义了类的对象a,但是由于某些操作是对象a被释放了,导致访问不了th1()函数,可以使用智能指针解决,c++章节有介绍
#include<iostream>
#include<thread>
class A{
public:
void th1(){
std::cout<<"hello"<<std::endl;
}
}
int main()
{
//A a;
std::shared_ptr<A> a= std::make_shared_ptr<A>();
std::thread t(th1,a);
//有操作释放了a,会出现访问错误,找不到a对象的地址,可以采用智能指针解决
t.join();
return 0;
}
=============================================
入口函数为类的私有成员函数,使用友元函数解决
#include<iostream>
#include<thread>
class A{
friend void thread_th1();
private:
void th1(){
std::cout<<"hello"<<std::endl;
}
}
void thread_th1(){
std::shared_ptr<A> a= std::make_shared_ptr<A>();
std::thread t(th1,a);
t.join();
}
int main()
{
thread_th1();
return 0;
}