
本文演示如何在Linux系统下的C++环境中,运用POSIX线程库(pthread)实现多线程编程。以下代码片段展示了创建和运行多个线程的基本方法:
<code class="c++">#include <iostream>
#include <pthread.h>
// 线程函数
void* thread_function(void* arg) {
int thread_id = *(static_cast<int*>(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;
}</code>编译运行:使用 g++ -o multi_thread_example multi_thread_example.cpp -pthread 编译,然后执行 ./multi_thread_example。
本文档主要讲述的是Linux系统下的shell编程入门;Shell编程有很多类似C语言和其他程序语言的特征,但是又没有编程语言那样复杂。Shell程序就是放在一个文件中的一系列Linux命令和实用程序,在执行的时候,通过Linux一个接着一个地解释和执行每个命令。感兴趣的朋友可以过来看看
24
此示例创建5个线程,每个线程打印其ID。 实际应用中,可能需要考虑线程同步机制(如互斥锁 pthread_mutex_t)以避免竞争条件和数据冲突。
以上就是C++中Linux多线程怎样实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号