Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Pthread argument

This is my code. It's very simple.

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

void *func(void *arg)
{
    printf("ID=%d\n", *(int*)arg);
    pthread_exit(NULL);
}

int main()
{
    pthread_t pt[4];
    int i;

    for (i = 0; i < 4; i++)
    {
        int temp = i;
        pthread_create(&pt[i], NULL, func, (void*)&temp);
    }
    sleep(1);
    return 0;
}

I compiled it:

gcc p_test.c -lpthread

I ran it. It printed 2 2 3 3. I ran it again. It printed 2 3 3 2.

My problem is:

Why was 2 or 3 printed twice?

Why didn't it print 1 3 2 0 or any other results?

like image 868
thlgood Avatar asked Dec 26 '22 23:12

thlgood


1 Answers

The major problem here is that you're taking the address of the local variable temp, and then using that pointer outside the scope of the variable - as soon as you exit one iteration of the loop, your pointer to temp becomes invalid and you must not dereference it.

like image 189
Philip Kendall Avatar answered Jan 09 '23 07:01

Philip Kendall