c++11 的future函数实际上是线程的高级封装。
先看一个线程
void foo(int &n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int n = 0;
std::thread t1(foo,std::ref(n));
std::thread::id t1_id = t1.get_id();
std::cout << "t1's id: " << t1_id << '\n';
t1.join();
std::cout << "the n is " << n<<std::endl;
getchar();
}
执行以后结果为:
Thread executing
t1’s id: 22864
Thread executing
Thread executing
Thread executing
Thread executing
the n is 5
ok,我们可以使用更为简单的方法来使用std::future,
int foo(int &n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return n;
}
//int main()
//{
// int n = 0;
// std::thread t1(foo,std::ref(n));
// std::thread::id t1_id = t1.get_id();
//
//
// std::cout << "t1's id: " << t1_id << '\n';
//
// t1.join();
// std::cout << "the n is " << n<<std::endl;
// getchar();
//}
int main()
{
int n = 0;
std::future<int> result = std::async(foo,std::ref(n));
std::cout << result.get() << std::endl;
getchar();
}
输出:
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
5
可以看到,我们使用
std::future<int> result = std::async(foo,std::ref(n));
std::cout << result.get() << std::endl;
这简短的两句话,就代替了所有的线程语句,看不到任何线程的启动和等待停止,result.get()会自动为我们阻塞等待结果。
httplib 是一个非常优秀的http协议封装,但成事在人,我们在使用的时候,如果一不小心就会发生:
1 socket阻塞
2 逻辑问题耗时
为了使得
例如以下这一段程序:
httplib::Client client(v_param->end_call.c_str());
const char *stret = "{\"type\":\"startLive\",\"ChapterId\":%d,"
"\"CourseId\":%d,"
"\"Url\":\"%s\","
"\"TUrl\":\"%s\","
"\"SUrl\":\"%s\",\"Statue\":0}";
char buffer[1024];
string s = v_param->surl.empty() ? "" : "student";
string t = v_param->turl.empty() ? "" : "teacher";
sprintf(buffer, stret, v_ChapterId, v_CourseId,
v_param->addr_flv.c_str(), t.c_str(), s.c_str());
//cout << buffer << endl;
httplib::Headers header = {
{ "token", v_token.c_str() }
};
auto res = client.Post("/api/v1/live_video_handle",
header,
buffer, strlen(buffer), "application/json");
if (res.error() == httplib::Error::Success)
{
cout << res->body << endl;
}
//停止直播
Stop_av(); //耗时等待
return 0;
以上的代码有两个地方可能会产生问题:
1 Post 可能会遇到阻塞
2 stop_av 可能会遇到阻塞
一旦遇到这种情况,我们可能会考虑这种方式:启动一个线程去做,不过,我们可以更为简单,使用std::future,将以上代码封装在一个函数里面,函数名称为result_future。
std::async(std::bind(&classname::result_future,this));
一句话,就避免了线程的管理,是不是很方便呢。