本文演示如何在Linux系統下的c++環境中,運用POSIX線程庫(pthread)實現多線程編程。以下代碼片段展示了創建和運行多個線程的基本方法:
#include <iostream> #include <pthread.h> // 線程函數 void* thread_function(void* arg) { int thread_id = *(static_cast<int*>(arg)); std::cout << "Thread " << thread_id << " is running. "; pthread_exit(nullptr); // 線程結束 return nullptr; } int main() { const int num_threads = 5; pthread_t threads[num_threads]; int thread_ids[num_threads]; // 創建線程 for (int i = 0; i < num_threads; ++i) { thread_ids[i] = i; if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) { std::cerr << "Failed to create thread " << i << ". "; return 1; } } // 等待線程結束 for (int i = 0; i < num_threads; ++i) { pthread_join(threads[i], nullptr); } std::cout << "All threads finished. "; return 0; }
編譯運行:使用 g++ -o multi_thread_example multi_thread_example.cpp -pthread 編譯,然后執行 ./multi_thread_example。
此示例創建5個線程,每個線程打印其ID。 實際應用中,可能需要考慮線程同步機制(如互斥鎖 pthread_mutex_t)以避免競爭條件和數據沖突。