Pthread arguments

I am having problems passing arguments to new threads, I have the following

 doRowOffset[0] = 0;
 for(threads = 1; threads < NUMTHREADS; threads++){
      doRowOffset[threads] = threads;
      printf("Do row: %d\n", doRowOffset[threads]);
      pthread_create(&threadHandler[threads], NULL, multiplyRows, (void *) &doRowOffset[threads]);



void * multiplyRows(void * dealWithRows){
        int offset = *((int *) dealWithRows);
        printf("%d\n", *((int *) dealWithRows));
        printf("Offset: %d\n", offset);
        printf("Size: %d\n", partitionSize/NUMTHREADS);
        printf("Calculated Offset: %d\n", offset*partitionSize/NUMTHREADS);


Now I expect to see the following output

Make line: 1
Offset: 1
Size: 2
Calculated offset: 2

However I keep getting garbage values ​​or 0 for dealWithRows, when I hit the thread, am I doing something wrong with passing the argument?


source to share

2 answers

If you pass the address to a variable that changes, you should expect it to change on you :-)

Which probably happens when you set doRowOffset

to 1 (for example) and then start the thread. Before this thread starts expanding and looks for its pointer, you swap doRowOffset

for the next thread.

Then when the first thread finally plays out the address, you changed the base value.

There are two ways to handle this. First, keeping the main thread and the child thread in sync so that the main thread waits until the child dereferences the variable and stores the value locally. Only then does the main thread change the variable for the next thread that it starts running. However, this kind hits the target of streams :-)

Another is converting the actual integer value (not the address) to a void pointer that is passed to the stream function. This will mean that the value will be copied onto the thread function stack, not at the address, and the main thread will not be able to influence it.

Something like:

pthread_create (&threadHandler[threads], NULL, multiplyRows,
    (void *) doRowOffset); // <<-- Note, removed the '&'.


in the main thread and:

int offset = (int) dealWithRows;


in the child thread.



If doRowOffset

is int

, you do not see the trash, unless the function thread creation is complete, and you have selected the variable on the stack, and it will be overwritten.

But note that there is only one variable and you are passing its address, so when the thread starts, it can see the updated value.

Pass the actual value:

pthread_create(&threadHandler[threads], NULL, multiplyRows, (void *) threads);

void * multiplyRows(void * dealWithRows){
    int offset = (int) dealWithRows);




All Articles