在#%#$#%@%@%$#%$#%#%#$%@_e206a54e97690c++e50cc872dd70ee896系统中,c++程序可以采用多种方式来实现多线程功能。以下是两种常见的实现方法:
方法一:利用POSIX线程(pthreads)库
POSIX线程库(pthreads)是unix-like操作系统(包括Linux)中广泛应用的多线程库。
示例代码:
#include <iostream> #include <pthread.h> <p>// 线程函数 void<em> thread_function(void</em> arg) { int thread_id = <em>(static_cast<int</em>>(arg)); std::cout << "Thread ID: " << thread_id << std::endl; return nullptr; }</p><p>int main() { pthread_t threads[5]; int thread_ids[5] = {1, 2, 3, 4, 5};</p><pre class="brush:php;toolbar:false">for (int i = 0; i < 5; ++i) { pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]); } for (int i = 0; i < 5; ++i) { pthread_join(threads[i], nullptr); } return 0;
}
编译与运行:
g++ -pthread -o multithread_example multithread_example.cpp ./multithread_example
方法二:使用c++11标准库中的头文件
C++11标准引入了
示例代码:
#include <iostream> #include <thread> #include <vector> <p>// 线程函数 void thread_function(int thread_id) { std::cout << "Thread ID: " << thread_id << std::endl; }</p><p>int main() { std::vector<std::thread> threads;</p><pre class="brush:php;toolbar:false">for (int i = 0; i < 5; ++i) { threads.emplace_back(thread_function, i + 1); } for (auto& thread : threads) { thread.join(); } return 0;
}
编译与运行:
g++ -std=c++11 -pthread -o multithread_example multithread_example.cpp ./multithread_example
总结
具体选择哪种方法应根据项目需求和环境来决定。
立即学习“C++免费学习笔记(深入)”;