c++ - 如何在C++代码中运行多个线程

标签 c++ multithreading c++11 mutex

我是 C++ 的初学者。我编写了一个程序来从一个数据库中提取数据并将这些数据存储到另一个数据库中。我只是想添加多个线程来加快进程。我希望通过两种方式做到这一点。

  1. 从第一个数据库中提取数据并将这些数据存储在内存中。 (在本例中,我需要两种 std::vector 类型的数据)
  2. 从数据库中提取数据时,如果 vector 大小超过10000,则需要调用并启动两个线程,从两个 vector (分别)获取数据并将这些数据存储在第二个 vector 中数据库。

考虑下面的例子。这是一个简单的代码来演示上述场景。有一个具有大量迭代的 for 循环。我需要为这段代码启动两个线程,以从 dataOne 和 dataTwo vector (两者都有单独的线程)中提取数据,并在 i = 10000 时将这些数据存储在 dataThree 和 dataFour vector 中>。

使用命名空间 std;

int main(){

   std::vector<std::vector<int>> dataOne;
   std::vector<std::vector<int>> dataTwo;

   std::vector<std::vector<int>> dataThree;
   std::vector<std::vector<int>> dataFour;

   for(int i=0; i < 10000000; i++){
       std::vector<int> temp = {1,2,3};
       dataOne.push_back(temp);          //store data in vector-one 

       std::vector<int> temp2 = {3,4,5};
       dataTwo.push_back(temp2);        //store data in vector-two      
   }
}

当 i=10000 时,应该有三个线程在运行,

  • 线程一 - 从 dataOne vector 获取数据并将其存储在 dataThree 中

  • 线程二 - 从 dataTwo vector 获取数据并将其存储在 dataFour 中

  • 主线程 - 在主函数中处理 for 循环

谁能帮我解决这个问题吗?

最佳答案

只需使用std::tread:cplusplus std::thread

我只是报告示例:

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread

void foo() 
{
  // do stuff...
}

void bar(int x)
{
  // do stuff...
}

int main() 
{
  std::thread first (foo);     // spawn new thread that calls foo()
  std::thread second (bar,0);  // spawn new thread that calls bar(0)

  std::cout << "main, foo and bar now execute concurrently...\n";

  // synchronize threads:
  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;
}

关于c++ - 如何在C++代码中运行多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545705/

相关文章:

c++ - 如果只创建一次,使用数百个线程是否安全?

C++如何检查两个类是否来自同一个对象

c++ - 在c/c++中使用变量作为对象名称的方法

c++ - 使用 Qt/C++ 确定 Google Drive 位置

ios - AFHTTPClient + enqueueBatchOfHTTPRequestOperations : handle cancellation and errors

java - 如何将变量传递给此 run() 函数?

c++ - istream_iterator 从流中消耗太多

c++ - 编译时指向函数错误的指针

c++ - 在 C++ 中遍历连续枚举值的最简单方法

c++ - 使非成员函数常量