C++多线程
1、线程的基本使用
1.1、使用基本库
#include <thread>
std::thread t(function_name, args...);
function_name
是线程入口点的函数或可调用对象
args...
是传递给函数的参数
创建线程后,我们可以使用t.join()
等待线程完成,或者使用t.detach()
分离线程,让它在后台运行。
1.2、join与detch
在一个线程中,开了另一个线程去干另一件事,使用join函数后,原始线程会等待新线程执行结束之后,再去销毁线程对象。
这样有什么好处?---->因为它要等到新线程执行完,再销毁,线程对象,这样如果新线程使用了共享变量,等到新线程执行完再销毁这个线程对象,不会产生异常。如果不使用join,使用detch,那么新线程就会与原线程分离,如果原线程先执行完毕,销毁线程对象及局部变量,并且新线程有共享变量或引用之类,这样新线程可能使用的变量,就变成未定义,产生异常或不可预测的错误。
所以,当你确定程序没有使用共享变量或引用之类的话,可以使用detch函数,分离线程。
但是使用join可能会造成性能损失,因为原始线程要等待新线程的完成,所以有些情况(前提是你知道这种情况,如上)使用detch会更好。
1.3、join使用
#include <iostream>
#include <thread>
void print_message(const std::string& message)
{
std::cout << message << std::endl;
}
int main() {
std::thread t1(print_message, "Thread 1");
std::thread t2(print_message, "Thread 2");
t1.join();
t2.join();
std::cout << "All threads joined" << std::endl;
return 0;
}
打印信息:
Thread 1
Thread 2
All threads joined
1.4、joinable使用
joinable()方法返回一个布尔值,如果线程可以被join()或detach(),则返回true,否则返回false。如果我们试图对一个不可加入的线程调用join()或detach(),则会抛出一个std::system_error异常。
#include <iostream>
#include <thread>
void foo() {
std::cout << "Thread started" << std::endl;
}
int main() {
std::thread t(foo);
if (t.joinable()) {
t.join();
}
std::cout << "Thread joined" << std::endl;
return 0;
}
打印信息:
Thread started
Thread joined
2、线程函数中的数据未定义错误
2.1、传递临时变量的问题
#include <iostream>
#include <thread>
void foo(int& x) {
x += 1;
}
int main() {
int x = 1; // 将变量复制到一个持久的对象中
std::thread t(foo, std::ref(x)); // 将变量的引用传递给线程
t.join();
std::cout << x << std::endl;
return 0;
}
2.2、传递指针或引用指向局部变量的问题
#include <iostream>
#include <thread>
void foo(int* ptr) {
std::cout << *ptr << std::endl; // 访问已经被销毁的指针
}
int main() {
int x = 1;
std::thread t(foo, &x); // 传递指向局部变量的指针
t.join();
return 0;
}
在这个例子中,我们定义了一个名为foo
的函数,它接受一个整型指针作为参数,并输出该指针所指向的整数值。然后,我们创建了一个名为t
的线程,将foo
函数以及指向局部变量x
的指针作为参数传递给它。这样会导致在线程函数执行时,指向局部变量x
的指针已经被销毁,从而导致未定义行为。
解决方案是将指针或引用指向堆上的变量,或使用std::shared_ptr
等智能指针来管理对象的生命周期。
使用new
#include <iostream>
#include <thread>
void foo(int* ptr) {
std::cout << *ptr << std::endl;
delete ptr; // 在使用完指针后,需要手动释放内存
}
int main() {
int* ptr = new int(1); // 在堆上分配一个整数变量
std::thread t(foo, ptr); // 将指针传递给线程
t.join();
return 0;
}
使用智能指针(std::shared_ptr)
#include <iostream>
#include <thread>
#include <memory>
void foo(std::shared_ptr<int> ptr) {
std::cout << *ptr + 1 << std::endl;
}
int main() {
std::shared_ptr<int> ptr = std::make_shared<int>(1); // 在堆上分配一个整数变量
std::cout << *ptr << std::endl;
std::thread t(foo, ptr); // 将指针传递给线程
t.join();
return 0;
}
2.3、错误示例:传递指针或引用指向已释放的内存的问题
#include <iostream>
#include <thread>
void foo(int* x) {
std::cout << *x << std::endl; // 访问已经被释放的内存
}
int main() {
int* ptr = new int(1);
std::thread t(foo, ptr); // 传递已经释放的内存
delete ptr;
t.join();
return 0;
}
2.4、错误示例:类成员函数作为入口函数,类对象被提前释放
#include <iostream>
#include <thread>
class MyClass {
public:
void func() {
std::cout << "Thread " << std::this_thread::get_id()
<< " started" << std::endl;
// do some work
std::cout << "Thread " << std::this_thread::get_id()
<< " finished" << std::endl;
}
};
int main() {
MyClass obj;
std::thread t(&MyClass::func, &obj);
// obj 被提前销毁了,会导致未定义的行为
return 0;
}
解决方案
#include <iostream>
#include <thread>
#include <memory>
class MyClass {
public:
void func() {
std::cout << "Thread " << std::this_thread::get_id()
<< " started" << std::endl;
// do some work
std::cout << "Thread " << std::this_thread::get_id()
<< " finished" << std::endl;
}
};
int main() {
std::shared_ptr<MyClass> obj = std::make_shared<MyClass>();
std::thread t(&MyClass::func, obj);
t.join();
return 0;
}
2.5、入口函数为类的私有成员函数
#include <iostream>
#include <thread>
class MyClass {
private:
friend void myThreadFunc(MyClass* obj);
void privateFunc(){
std::cout << "Thread "
<< std::this_thread::get_id() << " privateFunc" << std::endl;
}
};
void myThreadFunc(MyClass* obj) {
obj->privateFunc();
}
int main() {
MyClass obj;
std::thread thread_1(myThreadFunc, &obj);
thread_1.join();
return 0;
}
3、互斥量解决多线程数据共享问题
在多个线程中共享数据时,需要注意线程安全问题。如果多个线程同时访问同一个变量,并且其中至少有一个线程对该变量进行了写操作,那么就会出现数据竞争问题。数据竞争可能会导致程序崩溃、产生未定义的结果,或者得到错误的结果。
为了避免数据竞争问题,需要使用同步机制来确保多个线程之间对共享数据的访问是安全的。常见的同步机制包括互斥量、条件变量、原子操作等。
错误示例:t1和t2访问全局变量时,出现的shared_data值相同情况,无效加运算;
代码:交替访问全局变量
#include <iostream>
#include <thread>
#include <mutex>
int shared_data = 0;
std::mutex mtx;
void func(int n) {
for (int i = 0; i < 100; ++i) {
mtx.lock();
shared_data++;
std::cout << "Thread " << n <<"i:"<< i
<< " increment shared_data to " << shared_data << std::endl;
mtx.unlock();
}
}
int main() {
std::thread t1(func, 1);
std::thread t2(func, 2);
t1.join();
t2.join();
std::cout << "Final shared_data = " << shared_data << std::endl;
return 0;
}
部分打印信息
最终shared_data 值为200
4、线程死锁的情况
假设有两个线程 T1 和 T2,它们需要对两个互斥量 mtx1 和 mtx2 进行访问,而且需要按照以下顺序获取互斥量的所有权:
- T1 先获取 mtx1 的所有权,再获取 mtx2 的所有权。
- T2 先获取 mtx2 的所有权,再获取 mtx1 的所有权。
如果两个线程同时执行,就会出现死锁问题。因为 T1 获取了 mtx1 的所有权,但是无法获取 mtx2 的所有权,而 T2 获取了 mtx2 的所有权,但是无法获取 mtx1 的所有权,两个线程互相等待对方释放互斥量,导致死锁。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx1;
std::mutex mtx2;
void func1() {
for(int i = 0; i < 1000;i++){
mtx1.lock();
mtx2.lock();
mtx1.unlock();
mtx2.unlock();
}
}
void func2() {
for(int i = 0; i < 1000;i++){
mtx2.lock();
mtx1.lock();
mtx2.unlock();
mtx1.unlock();
}
}
int main() {
std::thread t1(func1);
std::thread t2(func2);
t1.join();
t2.join();
std::cout << __LINE__ << std::endl;
return 0;
}
5、lock_guard
std::lock_guard 是 C++ 标准库中的一种互斥量封装类,用于保护共享数据,防止多个线程同时访问同一资源而导致的数据竞争问题。
std::lock_guard 的特点如下:
-
当构造函数被调用时,该互斥量会被自动锁定。
-
当析构函数被调用时,该互斥量会被自动解锁。
-
std::lock_guard 对象不能复制或移动,因此它只能在局部作用域中使用。
#include <iostream>
#include <thread>
#include <mutex>
int shared_data = 0;
std::mutex mtx;
void func(int n) {
for (int i = 0; i < 100; ++i) {
std::lock_guard<std::mutex> lg(mtx);
shared_data++;
std::cout << "Thread " << n <<"i:"<< i
<< " increment shared_data to " << shared_data << std::endl;
}
}
int main() {
std::thread t1(func, 1);
std::thread t2(func, 2);
t1.join();
t2.join();
std::cout << "Final shared_data = " << shared_data << std::endl;
return 0;
}