欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > c/c++ >内容正文

c/c++

C++11中Thread类简单使用的例子

发布时间:2025/3/21 c/c++ 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C++11中Thread类简单使用的例子 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

代码如下:

#include <iostream> #include <thread> #include <chrono> #include <future> #include <cmath> #include <vector> #include <cstdlib>using namespace std; void helloworld() {cout << "hello world" <<endl; }double caculate(int v) {if (v <= 0) {return v;}this_thread::sleep_for(std::chrono::milliseconds(10));return sqrt((v * v + sqrt((v - 5) * (v + 2.5)) / 2.0) / v); }template<typename Iter,typename Fun> double visitRange(thread::id id, Iter iterBegin, Iter iterEnd, Fun fun) {auto curId = this_thread::get_id();if (id == this_thread::get_id()) {cout << curId << "main thread" << endl;}else {cout << curId << "worker thread" << endl;}double v = 0;for (auto iter = iterBegin; iter != iterEnd; ++iter) {v += fun(*iter);}return v; }int main() {auto mainThreadId = this_thread::get_id();vector<double> v;for (int i = 0; i < 1000; i++) {v.push_back(rand());}cout << v.size() << endl;double value = 0.0;auto st = clock();for (auto& info : v) {value += caculate(info);}auto ed = clock();cout << "single thread:" << value << " "<<ed - st << "time" << endl;auto iterMid = v.begin() + (v.size() / 2);double lastPart = 0.0;auto iterEnd = v.end();st = clock();//auto halfPart = visitRange(mainThreadId, v.begin(), iterMid, caculate);thread s([&lastPart, mainThreadId, iterMid, iterEnd]() {lastPart = visitRange(mainThreadId, iterMid, iterEnd, caculate);});auto halfPart = visitRange(mainThreadId, v.begin(), iterMid, caculate);s.join();ed = clock();cout << "multi thread: " << (halfPart + lastPart) << " " << ed - st << "time" << endl;return 0; }

Makefile:

CFLAGS=-std=c++11 -pthread CC=g++ pThreadTest:pThreadTest.cpp$(CC) $(CFLAGS) $^ -o $@ .PHONY:clean clean:$(RM) pThreadTest.o pThreadTest

 

总结

以上是生活随笔为你收集整理的C++11中Thread类简单使用的例子的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。