
本文演示如何在Linux系统下的C++环境中,运用POSIX线程库(pthread)实现多线程编程。以下代码片段展示了创建和运行多个线程的基本方法:
#include#include // 线程函数 void* thread_function(void* arg) { int thread_id = *(static_cast (arg)); std::cout << "Thread " << thread_id << " is running.\n"; 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 << ".\n"; return 1; } } // 等待线程结束 for (int i = 0; i < num_threads; ++i) { pthread_join(threads[i], nullptr); } std::cout << "All threads finished.\n"; return 0; }
编译运行:使用 g++ -o multi_thread_example multi_thread_example.cpp -pthread 编译,然后执行 ./multi_thread_example。
本文档主要讲述的是Linux系统下的shell编程入门;Shell编程有很多类似C语言和其他程序语言的特征,但是又没有编程语言那样复杂。Shell程序就是放在一个文件中的一系列Linux命令和实用程序,在执行的时候,通过Linux一个接着一个地解释和执行每个命令。感兴趣的朋友可以过来看看
此示例创建5个线程,每个线程打印其ID。 实际应用中,可能需要考虑线程同步机制(如互斥锁 pthread_mutex_t)以避免竞争条件和数据冲突。









