mysterious segmentation fault
Hi,
Here is the code:
Code:
#include <pthread.h>
#include <iostream>
#include <vector>
using namespace std;
vector<string> myVector[3];
vector<string>::iterator myVectorIterator;
void* function( void* parameters )
{
int* i = (int *)parameters;
bool keep = true;
cout << "This thread prints number " << *i << endl;
while(keep)
{
for( myVectorIterator = myVector[*i].begin();
myVectorIterator != myVector[*i].end();
myVectorIterator++ )
{
cout << "String thread : " << *myVectorIterator << endl;
sleep(1);
}
}
return NULL;
}
int main()
{
pthread_t thread_id[3];
//fill the vector
myVector[0].push_back("Stupid dam_n you");
myVector[0].push_back("I hate you!");
myVector[0].push_back("Could you die, please!");
myVector[1].push_back("I love you!");
myVector[1].push_back("Beautiful life...");
myVector[1].push_back("Sea coming from heaven...");
myVector[2].push_back("Peace mind...");
myVector[2].push_back("Glory of the heart!");
myVector[2].push_back("Kindness means happiness...");
for(int i=0; i<3; i++)
{
pthread_create( &thread_id[i], NULL, &function, &i );
}
for(int i=0; i<3; i++)
{
pthread_join(thread_id[i], NULL);
}
return 0;
}
I always get this output:
This thread prints number 0
String thread : Stupid dam_n you
This thread prints number 1
String thread : I love you!
This thread prints number 2
String thread : Peace mind...
String thread : Glory of the heart!
String thread : Kindness means happiness...
Segmentation fault
Why???? If I remove the sleep function, it is okay... but just for a while, it will segmentation fault at some point. The interesting part is when I remove the sleep function, the program will display string thread from first vector for couple seconds then when it started to display string thread from second vector, it get segmentation fault.
The output is like this:
String thread : Stupid dam_n you
String thread : I hate you!
String thread : Could you die, please!
String thread : Stupid dam_n you
String thread : I hate you!
String thread : Could you die, please!
String thread : Stupid dam_n you
String thread : I hate you!
String thread : Could you die, please!
String thread : Stupid dam_n you
String thread : I hate you!
String thread : Could you die, please!
String thread : Stupid dam_n you
String thread : I hate you!
String thread : Could you die, please!
String thread : Stupid dam_n you
String thread : I hate you!
String thread : Could you die, please!
you die, please!
String thread : I love you!
String thread : Beautiful life...
String thread : Sea coming from heaven...
Segmentation fault
What I want from my program is the program display the string thread fairly and no segmentation fault. How? Thank you.