《万行代码计划》
一起学习,共同成长
day01,50行代码 参考视频《C++游戏服务器开发视频教程||64-多线程编程,一种简单的应用》
#include #include #include// #include #include #include
//复杂运算 double caculate(double v){ if(v<=0){ return v; } return sqrt((v * v+std::sqrt((v-5)*(v+2.5))/2.0)/v); }
//for_each template<typename Iter,typename Fun> double visitRange(Iter iterBegin,Iter interEnd,Fun func){ double v = 0; for (auto i = iterBegin; i != interEnd; ++i){ v += func(*i); } return v; }
int main() { std::vector v; for (size_t i = 0; i < 10000000; i++){ v.push_back(rand()); } std::cout<<v.size()<<std::endl; double value = 0.0; for (auto& info:v){ value += caculate(info); } std::cout<<value<<std::endl; auto iter = v.begin()+(v.size()/2); //second double anotherv = 0.0; auto iterEnd = v.end(); // std::thread s(&anotherv,iter,iterEnd{ anotherv = visitRange(iter,iterEnd,caculate); });// //first part auto halfv = visitRange(v.begin(),iter,caculate); s.join();// std::cout<<(halfv+anotherv)<<std::endl; }
/* <<std::thread join/detach操作>> std::thread是c++11新引入的线程标准库,通过其可以方便的编写与平台无关的多线程程序,虽然对比针对平台来定制化多线程库会使性能达到最大, 但是会丧失了可移植性,这样对比其他的高级语言,可谓是一个不足。终于在c++11承认多线程的标准。
在使用std::thread的时候,对创建的线程有两种操作:等待/分离,也就是join/detach操作。 join()操作是在std::thread t(func)后“某个”合适的地方调用,其作用是回收对应创建的线程的资源,避免造成资源的泄露。 detach()操作是在std::thread t(func)后马上调用,用于把被创建的线程与做创建动作的线程分离,分离的线程变为后台线程, 其后,创建的线程的“死活”就与其做创建动作的线程无关,它的资源会被init进程回收。 */
/* 使用了c++11的thread库,运行出现了:
terminate called after throwing an instance of ‘std::system_error’
what(): Enable multithreading to use std::thread: Operation not permitted Aborted
解决:g++ -std=c++11 -pthread -Wl,–no-as-needed thread_test.cpp */
|