std::thread
是C++11标准库中用于创建和管理线程的类。它提供了一种简单且高效的方式来创建和管理多线程应用程序。以下是对std::thread
的详细介绍,以及一些示例代码。
创建线程
使用std::thread
创建线程非常简单,只需要将要在新线程中执行的函数(或可调用对象)传递给std::thread
的构造函数:
#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Thread is running." << std::endl;
}
int main() {
std::thread t(threadFunction); // 创建并启动线程
t.join(); // 等待线程完成
return 0;
}
传递参数给线程
可以通过构造函数将参数传递给线程函数:
#include <iostream>
#include <thread>
void threadFunction(int n) {
std::cout << "Thread received parameter: " << n << std::endl;
}
int main() {
std::thread t(threadFunction, 5); // 创建并启动线程,同时传递参数
t.join(); // 等待线程完成
return 0;
}
使用lambda表达式创建线程
还可以使用lambda表达式来创建线程:
#include <iostream>
#include <thread>
int main() {
std::thread t([] {
std::cout << "Thread is running using lambda." << std::endl;
});
t.join(); // 等待线程完成
return 0;
}
线程分离与合并
- 线程分离:使线程在后台运行,主线程不等待其完成。
- 线程合并:等待线程完成。
#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Thread is running." << std::endl;
}
int main() {
std::thread t(threadFunction);
// 分离线程
t.detach();
// 或者等待线程完成
// t.join();
std::cout << "Main thread is exiting." << std::endl;
return 0;
}
线程可移动但不可复制
std::thread
对象是不可复制的,但可以通过移动构造或移动赋值操作符将其移动:
#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Thread is running." << std::endl;
}
int main() {
std::thread t1(threadFunction);
std::thread t2 = std::move(t1); // 移动线程对象
t2.join(); // 等待线程完成
return 0;
}
使用互斥锁保护共享数据
在多线程编程中,访问共享数据时需要使用互斥锁来防止数据竞争:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void printMessage(const std::string& message, int count) {
for (int i = 0; i < count; ++i) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << message << ": " << i << std::endl;
}
}
int main() {
std::thread t1(printMessage, "Thread 1", 5);
std::thread t2(printMessage, "Thread 2", 5);
t1.join();
t2.join();
return 0;
}
在这个示例中,使用std::mutex
和std::lock_guard
来保护共享的标准输出流,防止多个线程同时访问它而导致的竞争条件。
总结
std::thread
是C++11引入的强大工具,极大简化了多线程编程。它提供了灵活和高效的方式来创建、管理和同步线程,使开发者能够轻松实现并发编程。但在使用多线程时,必须小心处理共享数据,避免竞争条件和死锁等问题。