miliardo18 miliardo18 - 3 years ago 128
C++ Question

c++ pthreads and struct's corrupting data

I'm new to pthreads and having a hard time creating a thread with a struct and keeping it's data intact while re-casting it from a void pointer.

I've spent days searching around trying to find a reason for this and haven't had much luck. Out of my two structures (using two different threads) one re-casts correctly in the thread, but for whatever reason, the second doesn't.


struct Arguments {
List linkedList;
Node node;
Arguments (List *newList, Node *newNode){
linkedList = *newList;
pcb = *newPCB;

struct ClockControl {
int counter = 0;
pthread_mutex_t lock;


void *schedule(void *args){

//Arguments *newArgs = static_cast<Arguments*>(args); <-- Tried this, doesn't work either.
arguments *newArgs = (arguments *) args;
List tempList = (newArgs ->linkedList); //DATA HERE IS CORRUPTED/WRONG
Node tempNode = (newArgs ->node); //DATA HERE IS CORRUPTED/WRONG

cout << "Flagged" << Lendl;

return NULL;

void *clockTime(void *clock){
//This thread works fine

clockControl *newClock = (clockControl*) clock;
int localVariable = 0;

localVariable = (newClock -> counter);

pthread_mutex_lock(&(newClock -> lock));
newClock->counter = localVariable;
pthread_mutex_unlock(&(newClock -> lock));

return NULL;


int main(int argc, char** argv)
pthread_t threads[NUM_THREADS]; //Defined as 5

clockControl clock;
clock.counter = 0;
pthread_mutex_init(&clock.lock, NULL);

//Lists are initialized with variables.
List pendingList = initializeList();
List readyList = initializeList();

Arguments *args = new Arguments(&readyList, &pendingList.head->info);

while (clock.counter < 6000){
pthread_create(&threads[1], NULL, clockTime, (void*) &clock);

if (clock.counter == pendingList.head->info.timeCreated){

pthread_create(&threads[0], NULL, schedule, (void*) &args);


//Clean up threads
for (int i = 0; i < 2; i++){

Like I said, I've searched around and pretty much spinning my wheels at this point. I have a suspicion it might be that the memory is being freed or cleaned up prior to the thread getting executed, but I can't find a way around it.

Any help would be appreciated.

Answer Source

You are passing the address of the pointer to args to your schedule function. When you use &args, args is already an Arguments* so you are passing an Arguments**. To solve this you can simply pass args by itself to the function.

Also just so you know, reinterpret_cast<Arguments*> is probably more appropriate than static_cast in this circumstance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download