samedi 26 mai 2018

How to run multiple threads in C++ code

I'm a beginner for c++. I wrote a program to extract data from one DB and store those data to another DB. I just want to add multiple threads to speed up the process. I hope to do this in two ways.

  1. Extract data from the first DB and store those data in memory. (In this case, I need to those data in two std::vector types)
  2. while extracting data from the database, if vector size is more than 10000, two threads need to invoke and need to start, get data from two vectors(separately) and store those data in the second database.

Consider the below example. It's a simple code to demonstrate the above scenario. There is a for-loop with huge iterations. I need to start two threads for this code to extract data from dataOne and dataTwo vectors (separate threads for both) and store those data in dataThree and dataFour vectors when the i = 10000.

using namespace 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      
   }
}

when i=10000, there should be three threads running,

  • Thread one - Getting data from dataOne vector and store in dataThree

  • Thread two - Getting data from dataTwo vector and store in dataFour

  • Thread main - process the for-loop in main function

anyone can help me to solve this?

Aucun commentaire:

Enregistrer un commentaire