描述:
std::thread是c++11引入的线程库的一部分,它允许开发人员通过创建独立的执行线程来执行并发任务。使用std::thread,我们可以轻松地将任务分配给不同的线程,并在不同线程之间进行通信和同步。
创建线程:
#include <iostream>
#include <thread>
#include <string>
void MyThread(const std::string& str)
{
std::cout << str << std::endl;
}
class CTest
{
public:
void MyThread(const std::string& str)
{
std::cout << str << std::endl;
}
};
int main()
{
std::string str = "hello world";
//lambda表达式
std::thread t1([str]() {
std::cout << str << std::endl;
});
if (t1.joinable())
t1.join();
//普通函数
std::thread t2(MyThread,str);
if (t2.joinable())
t2.join();
//成员函数
CTest t;
std::thread t3(&CTest::MyThread,&t,str);
if (t3.joinable())
t3.join();
return 0;
}
线程id:
#include <iostream>
#include <thread>
#include <string>
int main()
{
std::string str = "hello world";
//lambda表达式
std::thread t1([str]() {
std::cout << str << std::endl;
});
std::thread::id idMain = std::this_thread::get_id();
std::thread::id idT1 = t1.get_id();
std::cout << "main id " << idMain << std::endl;
std::cout << "t1 id " << idT1 << std::endl;
if (t1.joinable())
t1.join();
return 0;
}
线程休眠:
//休眠1秒
std::chrono::milliseconds sleeptime(1000);
std::this_thread::sleep_for(sleeptime);
类中创建线程:
#include <iostream>
#include <thread>
#include <atomic>
class CTest
{
public:
CTest()
{
m_bRunThread = true;
m_thread = std::thread(&CTest::MyThread,this);
}
~CTest()
{
m_bRunThread = false;
if (m_thread.joinable())
m_thread.join();
}
private:
void MyThread()
{
while (m_bRunThread)
{
std::cout << "hello world" << std::endl;
//休眠1秒
std::chrono::milliseconds sleeptime(1000);
std::this_thread::sleep_for(sleeptime);
}
}
private:
std::thread m_thread;
std::atomic<bool> m_bRunThread;
};
int main()
{
CTest t;
//休眠5秒
std::chrono::milliseconds sleeptime(5000);
std::this_thread::sleep_for(sleeptime);
return 0;
}