c++11 异步多线程优化fib 使用 future和async

本文探讨了C++11标准下多线程编程的优化技巧,通过使用std::async和std::future实现异步操作,显著提高了fib数列计算效率,将原本20多秒的单线程计算时间缩短至约13秒。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接: c++11 异步多线程优化fib 使用 future和async

对比国内这些, 写的都是些啥老玩意

多线程是节约时间的, 不跑跑代码咋知道有没有效果????

不过看看自己写的这垃圾, 也就算了吧

https://thispointer.com/c11-multithreading-part-2-joining-and-detaching-threads/

https://solarianprogrammer.com/2012/02/27/cpp-11-thread-tutorial-part-2/

https://thispointer.com/c11-how-to-create-vector-of-thread-objects/

https://thispointer.com/c11-multithreading-part-9-stdasync-tutorial-example/

wasm的支持好像有待提高....

相当的慢, 而且多线程一开直接web主线程无响应....

编译到node下也是问题有点多...

up-56b4cdfa08542da7ec8ba986ee1f6f1c69f.png

加了参数也无法执行

up-fdc0e90bf9d217124ec71fc7db2047b361c.png

两个耗时5s的操作串行执行耗时10s

#include <iostream>
#include <string>
#include <chrono>
#include <thread>
using namespace std::chrono;
std::string fetchDataFromDB(std::string recvdData)
{
    // Make sure that function takes 5 seconds to complete
    std::this_thread::sleep_for(seconds(5));
    //Do stuff like creating DB Connection and fetching Data
    return "DB_" + recvdData;
}
std::string fetchDataFromFile(std::string recvdData)
{
    // Make sure that function takes 5 seconds to complete
    std::this_thread::sleep_for(seconds(5));
    //Do stuff like fetching Data File
    return "File_" + recvdData;
}
int main()
{
    // Get Start Time
    system_clock::time_point start = system_clock::now();
    //Fetch Data from DB
    std::string dbData = fetchDataFromDB("Data");
    //Fetch Data from File
    std::string fileData = fetchDataFromFile("Data");
    // Get End Time
    auto end = system_clock::now();
    auto diff = duration_cast < std::chrono::seconds > (end - start).count();
    std::cout << "Total Time Taken = " << diff << " Seconds" << std::endl;
    //Combine The Data
    std::string data = dbData + " :: " + fileData;
    //Printing the combined Data
    std::cout << "Data = " << data << std::endl;
    return 0;
}

up-4897e98c06de98dc68ae61a5aee51017728.png

异步执行, 耗时5s

up-72d1298a1fb0e2dc2fe609f4d27d55ccb9d.png

#include <chrono>
#include <future>
#include <iostream>
#include <string>
#include <thread>
using namespace std::chrono;
std::string fetchDataFromDB(std::string recvdData) {
  // Make sure that function takes 5 seconds to complete
  std::this_thread::sleep_for(seconds(5));
  // Do stuff like creating DB Connection and fetching Data
  return "DB_" + recvdData;
}
std::string fetchDataFromFile(std::string recvdData) {
  // Make sure that function takes 5 seconds to complete
  std::this_thread::sleep_for(seconds(5));
  // Do stuff like fetching Data File
  return "File_" + recvdData;
}
int main() {
  // Get Start Time
  system_clock::time_point start = system_clock::now();
  std::future<std::string> resultFromDB =
      std::async(std::launch::async, fetchDataFromDB, "Data");
  // Fetch Data from File
  std::string fileData = fetchDataFromFile("Data");
  // Fetch Data from DB
  // Will block till data is available in future<std::string> object.
  std::string dbData = resultFromDB.get();
  // Get End Time
  auto end = system_clock::now();
  auto diff = duration_cast<std::chrono::seconds>(end - start).count();
  std::cout << "Total Time Taken = " << diff << " Seconds" << std::endl;
  // Combine The Data
  std::string data = dbData + " :: " + fileData;
  // Printing the combined Data
  std::cout << "Data = " << data << std::endl;
  return 0;
}

/*
g++ --std=c++11   -pthread  -lpthread fibThread2.cpp
*/

单线程版fib

45个fib,需要20多秒

up-d04860bb3f986c365094139b2c0ea69f036.png

#include <chrono>
#include <iostream>
#include <thread>
#include <time.h>
#include <vector>
#define LL long long
using namespace std;

int _fib(int n) { return n < 2 ? n : _fib(n - 1) + _fib(n - 2); }

int fib(int n) {
  auto st = std::chrono::steady_clock::now();
  int f = _fib(n);
  auto ed = std::chrono::steady_clock::now();
  auto duration =
      std::chrono::duration_cast<std::chrono::milliseconds>(ed - st).count();
  cout << "fib time: " << n << "->" << duration << endl;
  return f;
}

void single(int size) {
  vector<int> v;
  auto start = std::chrono::steady_clock::now();
  for (int i = 0; i < size; i++) {
    int f = fib(i);
    v.push_back(f);
    cout << "fib: " << i << " " << f << endl;
  }
  auto finish = std::chrono::steady_clock::now();
  auto duration =
      std::chrono::duration_cast<std::chrono::milliseconds>(finish - start)
          .count();
  cout << "single time: " << duration << endl;
  for (int i = 0; i < v.size(); i++)
    cout << "fib:" << i << " " << v[i] << endl;
}

int main() {
  int size = 45;
  single(size);
  return 0;
}
/*
single time:
24475548
24305800
20785245
24328843
single time: 2256069

 g++ --std=c++11  -lpthread fibThread.cpp
 g++ --std=c++11   -pthread  -lpthread fibSingle.cpp

*/

所谓的多线程

因为join的原因虽然阻塞了主线程但也是并行, 也是45个fib, 提高到14s左右

up-fa42cb25b290da6a0c43edb589b8d624a6b.png

其实由于join的原因看着也不太像是多个并行

up-1ad6d0c4e654dca711c07133814e7c0aa28.png

#include <chrono>
#include <iostream>
#include <pthread.h>
#include <thread>
#include <time.h>
#include <vector>
#define LL long long
using namespace std;

int _fib(int n) { return n < 2 ? n : _fib(n - 1) + _fib(n - 2); }

int fib(int n, int *res) {
  clock_t st = clock();
  *res = _fib(n);
  clock_t ed = clock();
  cout << "fib time: " << n << "->" << ed - st << endl;
  return *res;
}

void many(int size) {
  clock_t start = clock();
  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
  int list[size];
  vector<std::thread> v;
  for (int i = 0; i < size; i++) {
    std::thread t(fib, i, list + i); // 启动线程foo
    // v.push_back(t);
    v.push_back(std::move(t));
    std::cout << t.hardware_concurrency() << "-->" << t.native_handle()
              << std::endl; //可以并发执行多少个(不准确)
    // t.detach(); // 等待线程执行完成
  }
  for (int i = 0; i < v.size(); i++) {
    if (v[i].joinable())
      v[i].join(); // 等待线程执行完成
  }

  clock_t ends = clock();
  cout << "many time: " << ends - start << endl;
  for (int i = 0; i < size; i++) {
    cout << "fib: " << i << " " << *(list + i) << endl;
  }
}
int main() {
  int size = 45;
  many(size);
  // std::thread thread(fib);  // 启动线程foo
  // thread.join();  // 等待线程执行完成
  return 0;
}
/*
many time: 2234429
many time: 24892014
many time: 2156435
 g++ --std=c++11  -lpthread fibThread.cpp
 g++ --std=c++11   -pthread  -lpthread fibThread.cpp

*/

异步45个13秒

up-d4e4b48a0b6c36913c1ca48d6165a7cd7d9.png

有一点点并行的味道了

up-c994a766e45de1e3ee093689f75bad39a9a.png

#include <chrono>
#include <future>
#include <iostream>
#include <string>
#include <thread>
using namespace std::chrono;

int _fib(int n) {
  return n < 2 ? n : _fib(n - 1) + _fib(n - 2);
  ;
}

int fib(int n) {
  auto st = std::chrono::steady_clock::now();
  int f = _fib(n);
  auto ed = std::chrono::steady_clock::now();

  auto duration =
      std::chrono::duration_cast<std::chrono::milliseconds>(ed - st).count();
  std::cout << "fib time: " << n << " " << duration << std::endl;
  return f;
}

int main() {
  int size = 45;
  auto st = std::chrono::steady_clock::now();
  std::future<int> list[size];
  for (int i = 0; i < size; i++) {
    list[i] = std::async(std::launch::async, fib, i);
  }
  for (int i = 0; i < size; i++) {
    auto res = list[i].get();
    std::cout << "res:" << i << "-->" << res << std::endl;
  }
  auto ed = std::chrono::steady_clock::now();

  auto duration =
      std::chrono::duration_cast<std::chrono::milliseconds>(ed - st).count();
  std::cout << "future time: " << duration << std::endl;
  return 0;
}

/*
g++ --std=c++11   -pthread  -lpthread fibThread3.cpp
*/

以下是使用C语言编写的多线程程序来生成斐波那契数列的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define MAX_FIB 50 int fib[MAX_FIB]; void *calculate_fib(void *n) { int i; int *num = (int *)n; fib[0] = 0; fib[1] = 1; for (i=2; i<*num; i++) { fib[i] = fib[i-1] + fib[i-2]; } pthread_exit(NULL); } int main() { int n; pthread_t tid; printf("Enter the number of fibonacci numbers to generate (max %d): ", MAX_FIB); scanf("%d", &n); if (n > MAX_FIB) { printf("Error: maximum number of fibonacci numbers exceeded.\n"); exit(EXIT_FAILURE); } pthread_create(&tid, NULL, calculate_fib, &n); pthread_join(tid, NULL); printf("Fibonacci sequence:\n"); for (int i=0; i<n; i++) { printf("%d ", fib[i]); } printf("\n"); return 0; } ``` 在该程序中,我们首先定义了一个全局数组`fib`来存储生成的斐波那契数列。然后,我们创建了一个新的线程来计算斐波那契数列,并将线程ID存储在`tid`变量中。我们使用`pthread_create`函数来创建线程,该函数接受四个参数:线程ID,线程属性,线程函数传递给线程函数的参数。在本例中,我们将`calculate_fib`函数作为线程函数,并将要生成的斐波那契数列的数量作为参数传递。 `calculate_fib`函数接受一个指向整数的指针作为参数,并使用斐波那契数列的递推公式来计算每个数。然后,该函数将用`pthread_exit`函数退出线程。 在主函数中,我们使用`pthread_join`函数来等待线程的结束。`pthread_join`函数接受两个参数:线程ID指向线程返回值的指针。在本例中,我们只需要等待线程结束,因此第二个参数为`NULL`。 最后,我们输出生成的斐波那契数列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值