vendredi 15 septembre 2023

calculating sum of trapezoid with thread in c++

I have a problem related with threads when I try to calculate the sum of trapezoid for integration of x^2 using C++. Here is my example code :

#include<iostream>
#include <thread>
#include <vector>
#include <mutex>
using namespace std;

float y(float x)
{

    return (x*x);
}

float result;
// Function to evaluate the value of integral
float trapezoid(float a, float b, int n)
{
    float h = (b-a)/n;
    float s = y(a)+y(b);

    for (int i = 1; i < n; i++)
    {
        s += 2*y(a+i*h);
    }
    result += (h/2)*s;
}

// Driver program to test above function
int main()
{
    const int num_threads = 3;
    const int iteration = 600;

    float lb = 0;
    float hb = 0;
    float task_ = 1/num_threads;
    vector<thread> threads;

    for(hb = 0; hb<1; hb+=task_){

           threads.push_back(thread(&trapezoid,lb,hb,iteration));
           lb=hb;
    }
     // Wait for all threads to finish
    for (auto &thread : threads)
    {
        thread.join();
    }
    cout<<result<<endl;
    return 0;
}

I try to divide the task into several parts and calculate them using C++ STL threads but I only get this : enter image description here

do you know what is wrong with my code? I am still pretty much new on anything related with threads in C++..Any help for this is really appreciated.

Aucun commentaire:

Enregistrer un commentaire