学习网址
c++11中thread join和detach的区别
https://blog.csdn.net/c_base_jin/article/details/79233705C++11 std::thread在类的成员函数中的使用
https://www.cnblogs.com/c4isr/p/9205164.html
C++多线程编程 //这里讲的比较透彻
https://zhuanlan.zhihu.com/p/547312117
C++ thread::hardware_concurrency 获取硬件支持并发数
//获取获取硬件支持并发数
int nums = thread::hardware_concurrency();
std::cout<< "线程数量:" << nums<<std::endl;
std::this_thread::sleep_for: 休眠函数
//休眠函数,windows可代替Sleep,linux可代替sleep
std::this_thread::sleep_for(std::chrono::seconds(1));
std::chrono::hours(1) //1小时
std::chrono::minutes(1) //1分钟
std::chrono::seconds(1) //1秒
std::chrono::milliseconds(1) //1毫秒
std::thread的使用例子
#include <thread>
#include <iostream>
class demo {
public:
void p1() {
std::cout << "i am p1" << std::endl;
}
void p2(const char *arg1, unsigned arg2) {
std::cout << "i am p2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
//没有参数函数的例子
std::thread Thread1() {
return std::thread(&demo::p1, this);
}
//有参数的函数的例子
std::thread Thread2(const char *arg1, unsigned arg2) {
return std::thread(&demo::p2, this, arg1, arg2);
}
};
int main() {
demo *w = new demo();
std::thread t = w->Thread1();
t.join();
w->Thread2("hello", 100).detach();
return 0;
}
注意:
程序在退出之前,要等待线程结束
t.join() 这句是不能缺少的,如果缺了,在退出进程时会出现 Aborted(core dumped)
传类指针this给线程的例子
bool Client::create()
{
m_pThread = new std::thread(Client::Thread, this);
return true;
}
bool Client::Thread(void* pData)
{
Client * pThread = (Client *)pData;
if (pThread)
{
return pThread->ThreadRun();
}
return false;
}
bool Client::ThreadRun()
{
}
std::make_shared创建线程
void p3()
{
std::cout << "i am p3" << std::endl;
}
int main()
{
// 如果是临时创建就用auto
auto thread_new = std::make_shared<std::thread>(p3);
// 如果是在类里声明,
//std::shared_ptr<std::thread> thread_new = std::make_shared<std::thread>(p3);
std::thread* pThread = thread_new.get();
pThread->join();
// thread_new->join();
return 0;
}