Originally Posted by
Salem
> for(int i=0; i<3; i++)
As soon as this loop exists, all your threads are then pointing at a variable which no longer exists.
So when they dereference their pointer, the value they get (if they get anything at all) is anyones guess.
Ok, I change the code to:
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 damn 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...");
int a = 0;
int b = 1;
int c = 2;
//for( i=0; i<3; i++)
//{
pthread_create( &thread_id[a], NULL, &function, &a );
pthread_create( &thread_id[b], NULL, &function, &b );
pthread_create( &thread_id[c], NULL, &function, &c );
//}
for(int j=0; j<3; j++)
{
pthread_join(thread_id[j], NULL);
}
return 0;
}
The output is not fair at all:
This thread prints number 0
String thread : Stupid damn 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...
String thread : Peace mind...
String thread : Glory of the heart!
String thread : Kindness means happiness...
String thread : Peace mind...
String thread : Glory of the heart!
String thread : Kindness means happiness...
String thread : Peace mind...
String thread : Glory of the heart!
String thread : Kindness means happiness...
String thread : Peace mind...
String thread : Glory of the heart!
String thread : Kindness means happiness...
String thread : Peace mind...
String thread : Glory of the heart!
String thread : Kindness means happiness...
String thread : Peace mind...
String thread : Glory of the heart!
String thread : Kindness means happiness...
String thread : Peace mind...
How can I make the program to be more fair??? My program forgot that he has thread number one and two. My program prints thread number three only after it has printed thread number one and two once.