C++并发编程学习01——hello concurrent world

经典用例

#include 
#include 

void hello()
{
    std::cout << "hello concurrent world" << std::endl;
}

int main()
{
    std::thread t(hello);
    t.join();
}

编译

g++ -g test.cpp -o out -lpthread

gdb调试

(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

代码中注意点

  • 管理线程的函数和类在中声明,而保护共享数据的函数和类在其他
    头文件中声明
  • 每个线程都必须具有一个初始函数(initial function),新线程的执行从这个函数开始。对于应用程序来说,初始线程是main(),但是对于其他线程,可以在 std::thread 对象的构造函数中指定——本例中,被命名为 t 的 std::thread 对象使用新函数 hello()作为其初始函数。
  • 与直接写入标准输出或是从 main()调用 hello()不同,该程序启动了一个新的线程来实现,使线程数量增加到两个——初始线程始于 main(),而新线程始于hello()
  • 新的线程启动后,初始线程继续执行。如果它不等待新线程结束,它就将继续运行到main()的结尾,从而结束程序——这有可能发生在新线程运行之前。这就是为什么在这里调用 join()的原因,这会使得调用线程(在 main()中)等待与 std::thread
    对象相关联的线程,即这个例子中的 t。

你可能感兴趣的:(C++并发,c++,学习,开发语言)