在Linux中,C++多线程可以通过POSIX线程库(pthread)来实现。以下是一个简单的示例,展示了如何使用pthread创建和运行多个线程:
#include <iostream> #include <pthread.h> // 线程函数 void* thread_function(void* arg) { int thread_id = *(static_cast<int*>(arg)); std::cout << "线程 " << thread_id << " 正在运行" << std::endl; 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 << "创建线程失败" << std::endl; return 1; } } // 等待线程结束 for (int i = 0; i < num_threads; ++i) { pthread_join(threads[i], nullptr); } std::cout << "所有线程已结束" << std::endl; return 0; } 要编译这个程序,你需要链接pthread库。在命令行中,可以使用以下命令:
g++ -o multi_thread_example multi_thread_example.cpp -lpthread 然后运行生成的可执行文件:
./multi_thread_example 这个示例创建了5个线程,每个线程都会打印其线程ID。注意,线程的执行顺序是不确定的,因此输出的顺序可能会有所不同。
在实际应用中,你可能需要使用互斥锁(mutex)、条件变量(condition variable)等同步原语来确保线程之间的正确同步。这些同步原语也提供了在pthread库中。