C++ 多线程使用
Xhofe Lv3

C++ 多线程使用

最近在做C++的开发,其中很多地方需要使用到多线程,故记录在此。

头文件:#include <thread>,命名空间:std

std::thread是C++11之后的标准线程库,使用起来很方便。

主要有以下几种使用方式:

新线程执行一个函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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;
}
类外新线程执行一个成员函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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;
}
类中新线程执行成员函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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;
}
  • 本文标题:C++ 多线程使用
  • 本文作者:Xhofe
  • 创建时间:2020-10-01 14:08:00
  • 本文链接:https://nn.ci/posts/cpp-multithreading.html
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论