Linux環境下C++如何實現多線程

Linux環境下C++如何實現多線程

本文將演示如何在linux環境下使用c++和POSIX線程庫(pthread)創建多線程程序。 首先,確保你的系統已安裝pthread庫(大多數Linux發行版默認安裝)。

創建一個名為multithread_example.cpp的文件,并粘貼以下代碼:

#include <iostream> #include <pthread.h> #include <string>  // 線程函數 void* thread_function(void* arg);  int main() {     pthread_t thread1, thread2;     int result1, result2;      // 創建線程     result1 = pthread_create(&thread1, NULL, thread_function, (void*)"Thread 1");     result2 = pthread_create(&thread2, NULL, thread_function, (void*)"Thread 2");      if (result1 != 0 || result2 != 0) {         std::cerr << "Error creating thread" << std::endl;         return 1;     }      // 等待線程結束 (可選,取決于你的程序邏輯)     pthread_join(thread1, NULL);     pthread_join(thread2, NULL);      std::cout << "All threads finished." << std::endl;     return 0; }  void* thread_function(void* arg) {     std::string thread_name = static_cast<const char*>(arg);     std::cout << thread_name << " is running." << std::endl;     // 在這里添加你的線程任務代碼     return NULL; }

接下來,使用g++編譯器編譯代碼:

g++ -o multithread_example multithread_example.cpp -pthread

-pthread選項告訴編譯器鏈接pthread庫。

立即學習C++免費學習筆記(深入)”;

最后,運行生成的執行文件:

./multithread_example

該程序創建兩個線程,每個線程打印一條消息到控制臺。 pthread_join函數確保主線程等待子線程完成之后再退出。 你可以根據需要修改thread_function函數來執行不同的任務。 記住,在多線程編程中,需要仔細處理共享資源以避免數據競爭等問題。

? 版權聲明
THE END
喜歡就支持一下吧
點贊5 分享