最近在做C++的开发,其中很多地方需要使用到多线程,故记录在此。
头文件:#include <thread>,命名空间:std
std::thread是C++11之后的标准线程库,使用起来很方便。
主要有以下几种使用方式:
新线程执行一个函数类外新线程执行一个成员函数类中新线程执行成员函数
头文件:#include <thread>,命名空间:std
std::thread是C++11之后的标准线程库,使用起来很方便。
主要有以下几种使用方式:
新线程执行一个函数
- #include <iostream>
- #include <thread>
- using namespace std;
- void t1()
- {
- for (int i = 0; i < 10; ++i)
- {
- cout << "thread-1\n";
- }
- }
- void t2(int n)
- {
- for (int i = 0; i < n; ++i)
- {
- cout << "thread-2\n";
- }
- }
- int main()
- {
- thread th1(t1); //没有参数时
- thread th2(t2,10); //有参数时
- th1.join(); // 必须将线程join或者detach 等待子线程结束主进程才可以退出,detach是用来和线程对象分离的,这样线程会独立地执行
- th2.join();
- //or use detach
- //th1.detach();
- //th2.detach();
- cout << "main thread\n";
- return 0;
- }
- #include <iostream>
- #include <thread>
- using namespace std;
- class Client{
- void recieve();
- void recieve(int conn);
- }
- int main()
- {
- Client *client=new Client();//此处必须使用指针
- thread t1(&Client::recieve,client);//没有参数时
- thread t2(&Client::recieve,client,1);//有参数时
- t1.join();
- t2.join();
- return 0;
- }
- #include <iostream>
- #include <thread>
- using namespace std;
- class Client{
- void recieve();
- void recieve(int conn);
- Client(){
- thread t1(&Client::recieve,this);//没有参数时
- thread t2(&Client::recieve,this,1);//有参数时
- t1.detach();
- t2.detach();
- }
- }
- int main()
- {
- while(true){
- }
- return 0;
- }
"小礼物走一走,来肥宅自学平台支持我"
评论区
共条评论
- 这篇文章还没有收到评论,赶紧来抢沙发吧~
首页上页1下页尾页