#include<iostream>
#include<pthread.h>
#include<chrono>
struct Arg1{
int x,y;
};
void * process(void * threadarg){
int x,y;
Arg1 * myArg1;
myArg1 = (Arg1 *) threadarg;
x = myArg1->x;
y=myArg1->y;
int i=0;
while(i<500){
x+=1;
y+=2;
i++;
}
myArg1->x=x;
myArg1->y=y;
pthread_exit(NULL);
}
using namespace std;
int main(){
int x = 0;
int y = 0;
int n;
cin>>n;
Arg1 sharedObj;
sharedObj.x=x;
sharedObj.y=y;
auto start = chrono::high_resolution_clock::now();
pthread_t *threads = new pthread_t[n];
for(int i=0;i<n;++i){
pthread_create(&threads[i],NULL,process,(void *)&sharedObj);
}
for(int i=0;i<n;++i){
pthread_join(threads[i],NULL);
}
cout<<sharedObj.x<<" "<<sharedObj.y<<"\n";
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(stop-start);
cout<<duration.count()<<"\n";
}
I wrote this code to see if using shared variables cause problems in the result.
What it does is this- It first asks the user for number of threads n
. Each thread increments shared variables x and y by 1 and 2 respectively. Variables are shared via the use of the same struct object. In the end I print the values of x and y from the struct object.
I saw that for a small while loop in the function process
, I am able to get correct results, regardless the number of threads n. However, for large values, about 5000, I get wrong results sometimes.
Also, the time of execution increases with the number of threads, and I don't understand whether this is because of improper multithreading or because of overhead in creating more number of threads.
Thanks for any help in advance.
Unless we use a mutex or some method to ensure atomicity of write, we can not guarantee that we would get a correct value in pthreaded applications. This is because, simultaneous writes can lead to a race condition, with only one of the write affecting the shared variable.