除了使用 pthread_create
的方式建立新线程,还可使用 C++11 的线程 thread 类。ios
#include <iostream> #include <thread> #include <chrono> void fun1() { std::this_thread::sleep_for(std::chrono::seconds(20)); } void fun2() { std::this_thread::sleep_for(std::chrono::seconds(30)); } int main() { std::cout << "starting first helper..." << std::endl; std::thread helper1(fun1); std::cout << "starting second helper..." << std::endl; std::thread helper2(fun2); std::cout << "waiting for helpers to finish..." << std::endl; helper1.join(); helper2.join(); std::cout << "done." << std::endl; }
g++ -std=c++11 testThread.cc -o testThread
编译后运行c++
查看进程和线程 IDthis
titus@T64:~/practice/cpp/demo>ps -eLf | grep "testThread" pid ppid 线程id 线程个数 1033 8083 32033 8083 0 2 10:39 pts/67 00:00:00 ./testThread 1033 8083 32033 8085 0 2 10:39 pts/67 00:00:00 ./testThread 1033 8912 26760 8912 0 1 10:39 pts/8 00:00:00 grep testThread
能够看到有 testThread 进程在运行,进程中有两个线程 8083 和 8085 在运行。线程