本文介绍了Linux Pthread参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码.非常简单.
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;
}
我编译了它:
gcc p_test.c -lpthread
我跑了.打印2 2 3 3
.我又跑了一次.它打印了2 3 3 2
.
I ran it. It printed 2 2 3 3
. I ran it again. It printed 2 3 3 2
.
我的问题是:
为什么2
或3
打印两次?
为什么不打印1 3 2 0
或其他任何结果?
Why didn't it print 1 3 2 0
or any other results?
推荐答案
此处的主要问题是您要获取局部变量temp
的地址,然后在变量范围之外使用该指针-如退出循环的一次迭代后,指向temp
的指针将立即失效,并且您不得取消引用它.
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.
这篇关于Linux Pthread参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!