Linux Pthread argument

痞子三分冷 提交于 2019-12-23 15:10:41

问题


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?


回答1:


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.




回答2:


You're passing a pointer to a temporary variable into the thread creation function and this temporary goes out of scope at the end of the loop block. It would seem to me that the temporary address is being reused by the compiler and so that when the threads are executing, they see the same address location.

If you do:

int *temp = malloc(sizeof(int));
*temp = i;
pthread_create(&pt[i], NULL, func, (void*)temp);

instead, you should see the results you expect.

In this case, the thread function needs to free the int after it is printed it to avoid a memory leak.

Also, it's better practice to pthread_join() the threads that you're waiting for rather than just sleep()ing.




回答3:


because it prints temp, all threads shares the memory(why temp is "shared" is explained by TheJuice), so all threads "share" temp . Use a mutex or make temp a private variable. Private Variables in Threads

Or you can use phtread_join like this:

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

    for (i =0 ; i < 4; i++)
    {

      pthread_create(&pt[i], NULL, func, (void*)&i);
      pthread_join(pt[i],NULL);

    }

    //sleep(1);
    return 0;
}



回答4:


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

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

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

for (i =0 ; i < 4; i++)
{

    pthread_create(&pt[i], NULL, func, (void*)i);
    pthread_join(pt[i],NULL);
}



return 0;

}



来源:https://stackoverflow.com/questions/10881085/linux-pthread-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!