Nirav Bhatia
Nirav Bhatia

Reputation: 1033

argument passed to function in pthread_create

I'm experimenting with pthreads and for the following code:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void* print_thread_num(void *index);

int main(int argc, char** argv) {

    int i;
    pthread_t threads[3];

    for (i = 0; i < 3; i++) {
        void *index = &i;
        printf("Creating thread %d\n", i);
        pthread_create(&threads[i], NULL, print_thread_num, index);
    }
    pthread_exit(NULL);
}

void* print_thread_num(void *index) {
    int i = *(int*)index;
    printf("I am the thread at index %d\n", i);
    pthread_exit(NULL);
}

I'm getting the output below:

Creating thread 0
Creating thread 1
I am the thread at index 1
Creating thread 2
I am the thread at index 2
I am the thread at index 3

Why is each "I am the thread at index" printing an index higher than what it should print?

Upvotes: 0

Views: 129

Answers (1)

Gary
Gary

Reputation: 5732

You're passing the address of your loop variable i, this is being incremented in the main thread while your child threads access it.

Upvotes: 2

Related Questions