环境使用ubuntu18.04,使用POSIX这个库
1.创建一个线程,并执行
2.等待线程结束,并退出主函数。
完整example.cpp代码:
#include#include #include #include #include #include void * threadFunc(void * arg) { std::cout << "Thread Function :: Start" << std::endl; // Sleep for 2 seconds sleep(2); std::cout << "Thread Function :: End" << std::endl; return NULL; } int main() { // Thread id pthread_t threadId; // Create a thread that will function threadFunc() int err = pthread_create(&threadId, NULL, &threadFunc, NULL); // Check if thread is created sucessfuly printf("***********err:t%dn",err); if (err) { std::cout << "Thread creation failed : " << strerror(err); return err; } else std::cout << "Thread Created with ID : " << threadId << std::endl; // Do some stuff in Main Thread std::cout << "Waiting for thread to exit" << std::endl; // Wait for thread to exit err = pthread_join(threadId, NULL); // check if joining is sucessful if (err) { std::cout << "Failed to join Thread : " << strerror(err) << std::endl; return err; } std::cout << "Exiting Main" << std::endl; return 0; }
编译使用:
g++ example.cpp -lpthread
或cmake,CMakeLists.txt
cmake_minimum_required(VERSION 2.6) project(pthread_demo) add_executable(example example.cpp) target_link_libraries(example pthread)
运行后输出如下结果:
./a.out:



