Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to parallelize a program with OpenMP and I don't have any idea. The code below is a similar (very) semplified problem. I have a class whose attributes are a vector and its lenght. The method 'work' calculate each new element v[i] of the vector as the average value of the one before and the one after (considering periodic boundaries, ie element 0 is the average of element 1 and element (len-1)).
class:
#include<vector>
#include<iostream>
class A{
private:
std::vector<int> v;
int len;
public:
A(): len(0), v(0){
v[0] = 0;
}
A(unsigned n): len(n), v(n){
for(int i = 0; i < len; i++)
v[i] = 2*(i+1);
}
void work(){
std::vector<int> temp(len);
for(int i = 0; i < len; i++)
temp[i] = (v[((i-1+len)%len)] + v[((i+1)%len)]) / 2;
v.swap(temp);
}
void out(){
for(int i = 0; i < len; i++)
std::cout << v[i] << " ";
std::cout << std::endl;
}
~A(){}
};
main:
#include <iostream>
#include "omp.h"
#include "class.cpp"
int main () {
A a(5);
for(int i = 0; i < 10; i++){
a.work();
}
a.out();
return 0;
}
The method work is called multiple times. Can someone write me few lines of code to explain what to do?
I have the solution, in the method work of the class you have to write before the cycle:
#pragma omp parallel for
that's all!!!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I was asked to fill a given vector with prime numbers, I can't use any other vectors, arrays or collections. I've come up with something like this, but it doesn't work properly and I can't figure out why.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isPrime(int n){
if (n<=1){return false;}
for (int i = 2; i < n; i++){
if (n % i == 0){
return false;
}
}
return true;}
int fillWithPrimesVec(vector<int>& vec){
for (int i = 0; i < vec.size(); i++){
for (int j = 0; j<INT_MAX; j++){
if (isPrime(j)){
vec.push_back(j);}
else{continue;}
}
}
return vec[0];
}
int main(){
int c[15];
size_t szc = sizeof(c)/sizeof(*c);
vector<int> d(szc,0);
cout << fillWithPrimesVec(d);
return 0;
}
Could anyone please help me?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Question 1
I want to use multithreading fir computing Pi, but first i am trying to split the job across each thread
Question 2
there also a piece of code down there that computes the sample variance on an array of values. I want to also to use multithread on that part of the code. The algorithm needs two passes on the data and therefore introduce a need for some sort of synchronisation (a barrier in this case).
// LabClass.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <process.h>
#include <thread>
#include "Chrono.h"
//When performance is crucial, nbThreads should be the number of hardware threads supported
#define NB_THREADS 4
#define N 10000
int counter;
void HelloWorld(int id)
{
printf("Hello world from %d\n",id);
}
void HelloCPP11()
{
std::thread t[NB_THREADS];
//Launch
for (int i = 0; i < NB_THREADS; i++)
t[i] = std::thread(HelloWorld, i);
//Join
for (int i = 0; i < NB_THREADS; i++) {
t[i].join();
}
}
double PIEstimateAux(int n)
{
double sum=1;
double div=3.;
for (int i=0;i<n;i+=2)
{
sum=sum-1/div+1/(div+2);
div+=4;
}
return 4*sum;
}
void PIEstimate()
{
Chrono c;
double val=PIEstimateAux(N);
c.PrintElapsedTime_us("\nTime Pi (micro sec):");
std::cout << "\nPI estimate: " << val << "\n\n";
}
double SampleVarianceAux(int *t, int n)
{
double average=0;
double variance=0;
for (int i=0;i<n;i++)
average+=t[i];
average=average/(double) n;
for (int i=0;i<n;i++)
variance+=(t[i]-average)*(t[i]-average);
variance/=(n-1.);
return variance;
}
void SampleVariance()
{
//creating array of random numbers
int *t=new int[N];
if (t==NULL)
return ;
for (int i=0;i<N;i++)
t[i]=std::rand()%100;
Chrono c;
double val = SampleVarianceAux(t,N);
c.PrintElapsedTime_us("Variance time (micro sec):");
std::cout << "\nVariance estimate: " << val << "\n\n";
delete[] t;
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("\t\t\tSimple Hello world call\n");
HelloWorld(0);
HelloCPP11();
PIEstimate();
SampleVariance();
return 0;
}
Question 1
You need to create n threads in the same manner as HelloCPP11() and pass i to PieEstimateAux() as a thread ranking variable.
Use the thread ranking variable to work out the start and stop points in the for loop (eg. start = rank * (n / # threads) and stop = (rank + 1) * (n / # threads) and setup the for loop as for(int i = start; i < stop...){}.
Store 4 * sum in an array for each thread and sum them in the calling function after t[x].join()
Question 2
You need to split the function as the only real barrier using this threading technique is t[x].join(), so you'll have to create the threads with pt1 of the function, join them, and do it again with the next part.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm new to C++ and trying to populate and output a 12x12 array using pseudo-random numbers.
Can anyone see where the code is failing?
Code:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <random>
using namespace std;
const int i = 12;
const int j = 12;
int myArray [i] [j] = {0};
void generateArray();
int main()
{
generateArray();
return 0;
}
void generateArray()
{
srand(1234);
for(int i=0; i < 12; i++);
{
for(int j=0; j < 12; j++);
{
myArray[i][j]= rand();
}
cout << myArray[i][j] << " ";
}
}
Thanks,
Ryan
Your for loops have semicolons after their closing parentheses.
This will effectively treat the for loop as an empty body (and just ignore the loop in general).
Remove them and the code should execute.
Your for loop should look as below.
for(int i=0; i < 12; ++i)
{
for(int j=0; j < 12; ++j)
{
myArray[i][j]= rand();
cout << myArray[i][j] << " ";
}
cout << endl;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to make the elements of an array accessible, but I've had no success so far. This is the code, and I've created it due to the given assignment.
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class Matrix_1D
{
private:
int *p2values;
int num_elements;
public:
Matrix_1D(int *p2v, int n); // CTOR
~Matrix_1D(); // DTOR
void show();
};
Matrix_1D::Matrix_1D(int *p2v, int n)
{
n = sizeof(p2v)/sizeof(int); // the problem comes from the fact that sizeof(p2v) = 4 bytes, and not the length of the entire array!!!
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
Matrix_1D::~Matrix_1D()
{
delete [] p2values;
}
void Matrix_1D::show()
{
for(int i=0; i<num_elements; i++)
cout << p2values[i] << endl;
}
int main()
{
int array_a[] = {5,3,5};
Matrix_1D fkt_1D_a(array_a, sizeof(array_a)/sizeof(int));
fkt_1D_a.show();
system("pause");
return 0;
}
Matrix_1D::Matrix_1D(int *p2v, int n)
{
n = sizeof(p2v)/sizeof(int); // the problem comes from the fact that sizeof(p2v) = 4 bytes, and not the length of the entire array!!!
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
As you state the sizeof p2v is the size of the pointer so you have no idea how large the array is. Instead, use the parameter that is passed in and don't overwrite it:
Matrix_1D::Matrix_1D(int *p2v, int n)
{
// you don't need the first line at all.
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
The proper C++ way to get the size of your int array is to use a template:
template <typename T, size_t N>
size_t size(T (&)[N]) {
return N; // size of array
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was testing one of my classes, but for some reason I can't seem to cast an intiger from a 2d array to double. Here is my (very simplified) code:
In main.cpp
#include<iostream>
#include<conio.h>
#include<string>
#include "trajectories.h"
int main()
{
std::string response;
int numOfCoords;
int speed;
int ** coords;
std::cout<<"enter the number of coordinates: ";
std::cin>>numOfCoords;
std::cout<<"enter speed: ";
std::cin>>speed;
coords=new int *[numOfCoords];
for (int i=0; i<numOfCoords; i++)
coords[i] = new int[2];
for(int i=0; i<numOfCoords*2; i++)
{
if(i%2==0)
std::cout<<"enter point "<<i/2<<".x : ";
else
std::cout<<"enter point "<<i/2<<".y : ";
std::cin>>coords[i/2][i%2];
}
NPCTrajectory traj(numOfCoords, speed);
traj.AddCoordinates(coords);
std::cout<<coords[0][0]<<", "<<coords[0][1]<<std::endl;
getch();
double currentCoords[2];
currentCoords[0]=double(coords[0][0]);
currentCoords[1]=double(coords[0][1]);
for(;;)
{
traj.HandleEvents(currentCoords);
std::cout<<"current coordinates : ("<<currentCoords[0]<<", "<<currentCoords[1]<<")"<<std::endl;
std::cout<<"do you wish to continue? ";
getch();
}
}
Trajectories.h contains class declaration only, so I believe it is irrelevant. Here is my trajectories.cpp
#include "trajectories.h"
int FPSCap=5;
NPCTrajectory::NPCTrajectory(int npoints, int newSpeed)
{
numOfPoints=npoints;
this->speed=newSpeed;
points = new int * [npoints];
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
state = 0;
maxOffset=speed/FPSCap;
}
void NPCTrajectory::AddCoordinates(int ** coordinates)
{
for(int i=0;i<this->numOfPoints; i++)
{
points[i][0]=coordinates[i][0];
points[i][1]=coordinates[i][1];
}
}
void NPCTrajectory::HandleEvents(double (¤tCoordinates)[2])
{
if(state+1==numOfPoints) return;
if(Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1])<maxOffset) state++;
double ratio = maxOffset/Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1]);
currentCoordinates[0]+=(points[state+1][0]-currentCoordinates[0])*ratio;
currentCoordinates[1]+=(points[state+1][1]-currentCoordinates[1])*ratio;
}
Please note that removing command traj.AddCoordinates(coords) will make the problem disappear. Am I passing the array correctly to the function?
The problem is in your constructor NPCTrajectory. Replace npoints with loop variable i. The following code:
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
should be like:
for (int i=0; i<npoints; i++)
points[i] = new int[2];
Because of this incorrect allocation, you are getting error (segmentation fault) in AddCoordinates function when you try to access points[i][0] with i=0 (assuming you are giving npoints>0 in NPCTrajectory).