-
Pthreads...
I started using pthreads recently and tried to execute the following code in quad core processor..
Code:
#include <pthread.h>
#include<iostream>
#include <vector>
using namespace std;
vector<int> num;
void *threadfunc(void *arg)
{
int *input=(int*) arg;
for(int i=1;i<5;i++)
{
num.push_back((*input)*i);
}
return NULL;
}
int main()
{
pthread_t threadID[4];
void *exit_status;
for(int i=0;i<4;i++)
{
pthread_create(&threadID[i],NULL,threadfunc,&i);
}
for(int i=0;i<4;i++)
{
pthread_join(threadID[i],&exit_status);
}
for(int i=0;i<num.size();i++)
{
cout<<num[i]<<endl;
}
return 0;
}
Here is another version of same code
Code:
#include <pthread.h>
#include<iostream>
#include <vector>
using namespace std;
vector<int> num;
vector<int> contain;
void *threadfunc(void *arg)
{
num.clear();
int *input=(int*) arg;
for(int i=1;i<5;i++)
{
num.push_back((*input)*i);
}
//cout<<"K"<<endl;
return #
}
int main()
{
pthread_t threadID[4];
void *exit_status;
vector<int> *hold;
int count=0;
vector<int>:: iterator it;
void *threadfunc(void *arg);
it=contain.begin();
count=10;
for(int i=0;i<4;i++)
{
pthread_create(&threadID[i],NULL,threadfunc,&i);
}
for(int i=0;i<4;i++)
{
pthread_join(threadID[i],&exit_status);
hold=(vector<int> *)exit_status;
contain.insert(it,(*hold).begin(),(*hold).end());
(*hold).clear();
exit_status=NULL;
}
for(int i=0;i<contain.size();i++)
{
cout<<contain[i]<<endl;
}
return 0;
}
It compiles fine and gives an output in a single processor but in quad core, I get
Segmentation Fault (core dumped)
Kindly help....
-
wait...
you have one global variable num, right?
but it is accessed by several threads...
don't you think you should be careful on that...
i mean like putting putting some flags so that it won't be accessed by many threads at the same time...
correct me if i am wrong...
-
Look up mutexes. You need some sort of access control around num, at the very least. You also have concurrency problems with i, the variable you are passing to your threads. Go look up any threading tutorial, and read until they've taught you mutexes and deadlocks.