在C++中,可以使用标准库 <thread> 来实现多线程编程。以下是一个简单的示例,展示了如何在Linux环境下使用C++11的多线程功能:
#include <iostream>
#include <thread>
// 线程函数
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 创建一个线程
std::thread t(helloFunction);
// 等待线程完成
t.join();
std::cout << "Hello from the main thread!" << std::endl;
return 0;
}
要编译这个程序,你需要使用支持C++11的编译器,并且链接线程库。可以使用以下命令:
g++ -std=c++11 -pthread your_program.cpp -o your_program
然后运行生成的可执行文件:
./your_program
包含头文件:
#include <thread>
这个头文件包含了线程相关的定义和函数。
线程函数:
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
这是一个普通的函数,将被用作线程的执行体。
创建线程:
std::thread t(helloFunction);
这行代码创建了一个新的线程 t,并将 helloFunction 作为其执行体。
等待线程完成:
t.join();
调用 join() 方法会阻塞主线程,直到 t 线程完成执行。
std::mutex)来保护共享资源。thread_local 关键字来声明线程局部存储变量。#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 全局互斥锁
void printMessage(const std::string& msg) {
std::lock_guard<std::mutex> lock(mtx); // 自动管理锁
std::cout << msg << std::endl;
}
int main() {
std::thread t1(printMessage, "Hello from thread 1!");
std::thread t2(printMessage, "Hello from thread 2!");
t1.join();
t2.join();
return 0;
}
在这个示例中,printMessage 函数使用 std::lock_guard 来自动管理互斥锁,确保在同一时间只有一个线程可以访问 std::cout。
通过这些基本概念和示例,你应该能够在Linux环境下使用C++实现多线程编程。