C++并发与多线程(高级函数async)
async
在 C++ 中,async
关键字用于实现异步编程,它允许你定义异步操作,这些操作可以在后台执行,而不会阻塞当前线程。这是 C++11 引入的特性,与 std::async
函数和 std::future
类一起使用。与thread函数模板的区别在于async可以有返回值,thread无返回值。
简单入门
// ConsoleApplication10.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <thread>
#include <mutex>
#include <cstdint>
#include <future>
#include <list>
using namespace std;
int mythread()
{
cout << "func " << " threadid = " << this_thread::get_id() << " start " << endl << endl;
std::chrono::milliseconds dura(3000);
std::this_thread::sleep_for(dura);
cout << "func " << " threadid = " << this_thread::get_id() <<" end " << endl << endl;
return 5;
}
int main()
{
cout << "=========================================== " << " threadid = " << this_thread::get_id() << endl << endl;
std::future<int> ret = std::async(mythread);
cout << ret.get() << endl; //堵塞获取值,注意:get函数只能调用一次,不能多次调用
cout << "=========================================== " << " threadid = " << this_thread::get_id() << endl << endl;
return 0;
}
中级过度
// ConsoleApplication10.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <thread>
#include <mutex>
#include <cstdint>
#include <future>
#include <list>
using namespace std;
class A
{
public:
int mythread(int myint)
{
cout << "func " << " threadid = " << this_thread::get_id() << " start " << endl << endl;
cout << "myint = " << myint << endl;
std::chrono::milliseconds dura(3000);
std::this_thread::sleep_for(dura);
cout << "func " << " threadid = " << this_thread::get_id() << " end " << endl << endl;
return 5;
}
};
int main()
{
cout << "=========================================== " << " threadid = " << this_thread::get_id() << endl << endl;
A a;
int num = 100;
std::future<int> ret = std::async(&A::mythread,&a,num);//传入可调用对象 &a == std::ref(a)都是引用传递 相当于传递了this指针。
cout << ret.get() << endl; //堵塞获取值
cout << "=========================================== " << " threadid = " << this_thread::get_id() << endl << endl;
return 0;
}
其他线程使用可以参数我主页中的 C语言:高级并发操作(线程)文章。