user3404592
user3404592

Reputation: 11

pthread with struct argument not working

Upvotes: 0

Views: 311

Answers (1)

Joachim Isaksson
Joachim Isaksson

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

Related Questions