经典用例
#include <iostream>
#include <thread>
void hello()
{
std::cout << "hello concurrent world" << std::endl;
}
int main()
{
std::thread t(hello);
t.join();
}
编译文章来源:https://www.toymoban.com/news/detail-664954.html
g++ -g test.cpp -o out -lpthread
gdb调试文章来源地址https://www.toymoban.com/news/detail-664954.html
(gdb) r
Starting program: /usr1/code/ch1/out
Missing separate debuginfos, use: zypper install glibc-debuginfo-2.22-100.15.4.x86_64
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
[New Thread 0x7ffff6f79700 (LWP 17902)]
hello concurrent world
[Thread 0x7ffff6f79700 (LWP 17902) exited]
[Inferior 1 (process 17898) exited normally]
Missing separate debuginfos, use: zypper install libgcc_s1-debuginfo-8.2.1+r264010-1.3.3.x86_64 libstdc++6-debuginfo-8.2.1+r264010-1.3.3.x86_64
(gdb) c
The program is not being run.
(gdb) info threads
No threads.
(gdb) b dm_01_01.cpp:11
Breakpoint 1 at 0x400d53: file dm_01_01.cpp, line 11.
(gdb) r
Starting program: /usr1/code/ch1/out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
Breakpoint 1, main () at dm_01_01.cpp:11
11 std::thread t(hello);
(gdb) n
[New Thread 0x7ffff6f79700 (LWP 18588)]
hello concurrent world
[Thread 0x7ffff6f79700 (LWP 18588) exited]
12 t.join();
(gdb) info threads
Id Target Id Frame
* 1 Thread 0x7ffff7fda740 (LWP 18504) "out" main () at dm_01_01.cpp:12
(gdb) d
Delete all breakpoints? (y or n) y
(gdb) b dm_01_01.cpp:6
Breakpoint 2 at 0x400d2b: file dm_01_01.cpp, line 6.
(gdb) c
Continuing.
[Inferior 1 (process 18504) exited normally]
(gdb) r
Starting program: /usr1/code/ch1/out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
[New Thread 0x7ffff6f79700 (LWP 18896)]
[Switching to Thread 0x7ffff6f79700 (LWP 18896)]
Thread 2 "out" hit Breakpoint 2, hello () at dm_01_01.cpp:6
6 std::cout << "hello concurrent world" << std::endl;
(gdb) info threads
Id Target Id Frame
1 Thread 0x7ffff7fda740 (LWP 18895) "out" 0x00007ffff7bc7a0d in pthread_join ()
from /lib64/libpthread.so.0
* 2 Thread 0x7ffff6f79700 (LWP 18896) "out" hello () at dm_01_01.cpp:6
(gdb) c
Continuing.
hello concurrent world
[Thread 0x7ffff6f79700 (LWP 18896) exited]
[Inferior 1 (process 18895) exited normally]
(gdb) q
代码中注意点
- 管理线程的函数和类在
<thread>
中声明,而保护共享数据的函数和类在其他
头文件中声明 - 每个线程都必须具有一个初始函数(initial function),新线程的执行从这个函数开始。对于应用程序来说,初始线程是main(),但是对于其他线程,可以在 std::thread 对象的构造函数中指定——本例中,被命名为 t 的 std::thread 对象使用新函数 hello()作为其初始函数。
- 与直接写入标准输出或是从 main()调用 hello()不同,该程序启动了一个新的线程来实现,使线程数量增加到两个——初始线程始于 main(),而新线程始于hello()
- 新的线程启动后,初始线程继续执行。如果它不等待新线程结束,它就将继续运行到main()的结尾,从而结束程序——这有可能发生在新线程运行之前。这就是为什么在这里调用 join()的原因,这会使得调用线程(在 main()中)等待与 std::thread
对象相关联的线程,即这个例子中的 t。
到了这里,关于C++并发编程学习01——hello concurrent world的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!