温馨提示×

Ubuntu上C++多线程编程指南

c++
小樊
84
2024-09-04 10:28:34
栏目: 编程语言

在Ubuntu上进行C++多线程编程,你需要使用C++11标准或更高版本的编译器(如g++)以及相应的库

  1. 安装支持C++11的编译器:

确保你的系统中已经安装了支持C++11的编译器。对于Ubuntu,你可以使用g++编译器。通过以下命令安装g++:

sudo apt-get update
sudo apt-get install g++
  1. 创建一个简单的多线程程序:

创建一个名为multithreading_example.cpp的文件,并添加以下代码:

#include<iostream>
#include<thread>

void print_hello() {
    std::cout << "Hello from thread "<< std::this_thread::get_id()<< std::endl;
}

int main() {
    std::thread t1(print_hello);
    std::thread t2(print_hello);

    t1.join();
    t2.join();

    return 0;
}

这个程序创建了两个线程,每个线程都会执行print_hello函数。

  1. 编译和运行程序:

使用以下命令编译程序:

g++ -std=c++11 multithreading_example.cpp -o multithreading_example -pthread

注意,-std=c++11选项告诉编译器使用C++11标准,-pthread选项则链接了pthread库,这是实现多线程所必需的。

编译完成后,运行程序:

./multithreading_example

你将看到类似以下的输出:

Hello from thread 140390856775680
Hello from thread 140390848773376

每次运行程序时,线程ID可能会有所不同。

  1. 学习更多关于C++多线程的知识:

以上示例展示了如何在Ubuntu上创建一个简单的多线程C++程序。要深入了解C++多线程编程,你可以参考以下资源:

  • C++ Concurrency in Action, Second Edition by Anthony Williams
  • The C++ Programming Language by Bjarne Stroustrup
  • C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis
  • cppreference.com

祝你在Ubuntu上的C++多线程编程愉快!

0