阅读量:2
在 Linux 上使用 C++ 开发多线程程序,你可以使用 C++11 标准中的 库
- 包含头文件:
#include
#include
#include
- 创建一个函数,该函数将在新线程中运行:
void print_numbers() {
for (int i = 0; i < 10; ++i) {
std::cout << "Thread ID: " << std::this_thread::get_id() << ", Number: "<< i << std::endl;
}
}
- 在
main函数中创建线程对象,并将要运行的函数作为参数传递:
int main() {
// 创建一个线程对象
std::thread t(print_numbers);
// 等待线程完成
t.join();
return 0;
}
- 编译并运行程序:
g++ -std=c++11 -pthread your_file_name.cpp -o your_executable_name
./your_executable_name
如果你需要创建多个线程,可以使用 std::vector 存储线程对象,然后遍历向量并为每个元素调用 join() 或 detach() 方法。例如:
#include
#include
#include
void print_numbers(int start, int end) {
for (int i = start; i < end; ++i) {
std::cout << "Thread ID: " << std::this_thread::get_id() << ", Number: "<< i << std::endl;
}
}
int main() {
const int num_threads = 4;
const int numbers_per_thread = 10;
// 创建一个线程向量
std::vector threads;
// 为每个线程分配任务
int range = numbers_per_thread / num_threads;
int start = 0;
for (int i = 0; i < num_threads; ++i) {
int end = start + range;
if (i == num_threads - 1) {
end = numbers_per_thread; // 最后一个线程处理剩余的数字
}
threads.emplace_back(print_numbers, start, end);
start = end;
}
// 等待所有线程完成
for (auto& t : threads) {
t.join();
}
return 0;
}
这个示例将创建 4 个线程,每个线程打印 10 个数字。注意,你需要根据你的需求调整线程数量和任务分配。
以上就是关于“linux c++多线程咋开发”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm