本文演示如何在Linux系統(tǒng)下的c++環(huán)境中,運(yùn)用POSIX線程庫(kù)(pthread)實(shí)現(xiàn)多線程編程。以下代碼片段展示了創(chuàng)建和運(yùn)行多個(gè)線程的基本方法:
#include <iostream> #include <pthread.h> // 線程函數(shù) void* thread_function(void* arg) { int thread_id = *(static_cast<int*>(arg)); std::cout << "Thread " << thread_id << " is running. "; pthread_exit(nullptr); // 線程結(jié)束 return nullptr; } int main() { const int num_threads = 5; pthread_t threads[num_threads]; int thread_ids[num_threads]; // 創(chuàng)建線程 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; } } // 等待線程結(jié)束 for (int i = 0; i < num_threads; ++i) { pthread_join(threads[i], nullptr); } std::cout << "All threads finished. "; return 0; }
編譯運(yùn)行:使用 g++ -o multi_thread_example multi_thread_example.cpp -pthread 編譯,然后執(zhí)行 ./multi_thread_example。
此示例創(chuàng)建5個(gè)線程,每個(gè)線程打印其ID。 實(shí)際應(yīng)用中,可能需要考慮線程同步機(jī)制(如互斥鎖 pthread_mutex_t)以避免競(jìng)爭(zhēng)條件和數(shù)據(jù)沖突。