c++的std::thread和std::move

最近经常使用thread类,如果需要在线程创建后,对其灵活控制,有两种方法:

1、定义成全局变量

2、定义成类成员变量

记录一下学习过程。

一、工程创建

用VS2022创建一个CMake工程ThreadTest,在ThreadTest.cpp中填入一段代码

// ThreadTest.cpp: 定义应用程序的入口点。

#include "ThreadTest.h"
#include <thread>

using namespace std;

void add(int a, int b)
{
	int res = a + b;
	cout << a << "+" << b << "=" << res << endl;

	int i = 0;
	while(i++ < res)
	{
		cout << "i=" << i << endl;
	}
}

int main()
{
	cout << "Hello CMake." << endl;

	thread t1(add, 1, 2);
	t1.join();

	return 0;
}

 直接 ctrl+F5 运行程序,可以正常跑。

二、加入全局变量

第一部分的线程t1是个临时变量,创建后,不利于全局控制。因此创建一个全局变量t

// ThreadTest.cpp: 定义应用程序的入口点。

#include "ThreadTest.h"
#include <thread>

using namespace std;

void add(int a, int b)
{
	int res = a + b;
	cout << a << "+" << b << "=" << res << endl;

	int i = 0;
	while(i++ < res)
	{
		cout << "i=" << i << endl;
	}
}

std::thread t;

int main()
{
	cout << "Hello CMake." << endl;

	thread t1(add, 1, 2);
	t = t1;//这一行编译报错
	t.join();

	return 0;
}

但是编译报错了:

编译器提示,尝试引用已经删除的函数。这行代码错误解析如下:

1、thread t1(add, 1, 2);这行代码执行完后,t1作为一个临时变量就已经被删除了,没有办法赋值给全局变量t。

2、thread类不支持拷贝构造。详见参考文章【2】

3、t1是一个右值,是其地址无法通过解引用获得的值。

解决这个错误的办法是用std::move, 它能够返回传入参数的右值引用,详见参考文章【1】

// ThreadTest.cpp: 定义应用程序的入口点。

#include "ThreadTest.h"
#include <thread>

using namespace std;

void add(int a, int b)
{
	int res = a + b;
	cout << a << "+" << b << "=" << res << endl;

	int i = 0;
	while(i++ < res)
	{
		cout << "i=" << i << endl;
	}
}

std::thread t;

int main()
{
	cout << "Hello CMake." << endl;

	thread t1(add, 1, 2);
	//t = t1;//这一行编译报错
	t = move(t1);
	t.join();

	return 0;
}

可以看到,move函数很好完成了使命:把右值引用t1返回给了全局变量t。

 三、加入类封装

c++作为面向对象语言,用全局变量显得有些不合适,那就加一个MyThread类吧。

// ThreadTest.cpp: 定义应用程序的入口点。

#include "ThreadTest.h"
#include <thread>

using namespace std;

class MyThread
{
public:
	MyThread(int a, int b);
	void add(int a, int b);
	void wait();
private:
	thread m_thread;
};

MyThread::MyThread(int a, int b)
{
	thread t2(&MyThread::add, this, a, b);
	m_thread = move(t2);
}

void MyThread::add(int a, int b)
{
	int res = a + b;
	cout << a << "+" << b << "=" << res << endl;

	int i = 0;
	while (i++ < res)
	{
		cout << "i=" << i << endl;
	}
}

void MyThread::wait()
{
	m_thread.join();
}


void add(int a, int b)
{
	int res = a + b;
	cout << a << "+" << b << "=" << res << endl;

	int i = 0;
	while(i++ < res)
	{
		cout << "i=" << i << endl;
	}
}

//std::thread t;

int main()
{
	cout << "Hello CMake." << endl;

	//thread t1(add, 1, 2);
	//t = t1;//这一行编译报错
	//t = move(t1);
	//t.join();

	MyThread myThread(1, 2);
	myThread.wait();

	return 0;
}

ctrl+F5运行一下,正常工作。

 参考文献:

C++11中std:move()的作用和用法_grf123的博客-优快云博客_std::move()

C++多线程:std::thread_胖小迪的博客-优快云博客_c++ std::thread

### C++ 中 `std::thread` 的使用方法 #### 创建线程 为了创建一个新的线程,可以实例化一个 `std::thread` 对象并传递给其构造函数想要在线程中运行的任务。这个任务通常是一个函数或 lambda 表达式。 ```cpp #include <iostream> #include <thread> void backgroundTask() { std::cout << "Running on a separate thread." << std::endl; } int main() { std::thread t(backgroundTask); } ``` 当不再需要线程时,应该调用 `join()` 或者 `detach()` 方法来释放资源[^1]。 #### 加入线程 (`join`) 通过调用 `join()` 可以等待线程完成工作后再继续执行后续代码: ```cpp t.join(); // 主线程在此处暂停直到子线程结束 ``` #### 分离线程 (`detach`) 分离线程意味着让新启动的线程独立于主线程之外运行,而不需要显式的同步机制: ```cpp t.detach(); // 子线程将继续异步执行直至完成自己的生命周期 ``` #### 获取线程ID 可以通过 `get_id()` 函数获得当前线程的身份标识符: ```cpp auto id = t.get_id(); std::cout << "Thread ID is " << id << std::endl; ``` #### 检测是否可加入 要判断某个线程对象关联的实际操作系统级别的线程是否存在且未被回收,则可以用 `joinable()` 成员函数来进行测试: ```cpp if (t.joinable()) { // 如果该条件成立则表示存在有效的工作线程可供连接 } ``` #### Lambda表达式作为参数传入 也可以利用lambda表达式向线程传递额外的数据,在下面的例子中展示了如何捕获局部变量以及外部作用域内的数据结构: ```cpp #include <iostream> #include <string> #include <thread> int main(){ int local_state=0; auto func=[&local_state]() mutable -> void{ ++local_state; std::cout<<"Local state:"<<local_state<<'\n'; }; std::thread(func).join(); } ``` #### 处理返回值 对于那些有返回值得情况,我们可以借助 `std::promise`, `std::future` `std::packaged_task` 来实现跨线程间的安全通信与协调: ```cpp #include <iostream> #include <memory> #include <future> #include <utility> #include <functional> using namespace std; double divide(double a,double b){ if(b==0) throw runtime_error("Division by zero!"); return a/b; } int main(){ packaged_task<double(double,double)> task(divide); future<double> result=task.get_future(); thread td(move(task),2.0,4.0); try{ cout<<result.get()<<endl;//阻塞在这里直到得到结果 } catch(exception const&e){ cerr<<e.what()<<endl; } td.join(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值