Reputation: 11
I have read some posts and it seems it is still not working properly for this simple pthread problem that I am working. Any suggestions as to where I did wrong? I keep getting garbage instead of numbers from 0 to 5, randomly.
#define num_threads 6
pthread_mutex_t mutex;
pthread_t threads[num_threads];
struct argument
{
int value;
};
void* fun(void* args)
{pthread_mutex_lock(&mutex);
argument* args2=(argument*)args;
cout<<args2->value<<endl;
pthread_mutex_unlock(&mutex);
}
int main()
{pthread_mutex_init(&mutex,NULL);
for (long i=0;i<num_threads;i++)
{argument* args=new argument;
args->value=i;
pthread_create(&(threads[i]),NULL,fun,(void*) args);
delete args;
}
for (long i=0;i<num_threads;i++)
{pthread_join(threads[i],NULL);}
pthread_exit(NULL);
}
Upvotes: 0
Views: 311
Reputation: 181067
You're not handling memory correctly;
// Allocate memory for argument
argument* args=new argument;
// Set value
args->value=i;
// Create a thread, passing a pointer to argument as a parameter
pthread_create(&(threads[i]),NULL,fun,(void*) args);
// Free the argument you just passed.
// The pointer you just passed is no longer pointing to valid memory
// when the thread actually starts.
delete args;
In this case, allocating/passing the argument as you do, but removing the delete
in the main thread and allowing the thread to delete its own argument once it has finished using it is probably the easiest option.
Upvotes: 1