C pthread_自返回不同的值
我正在用C学习线程,发现了下面的“Hello World”程序。当我使用pthread_join()在线程内和线程外打印pthread_value()的值时,两个线程返回的值完全不同C pthread_自返回不同的值,c,pthreads,C,Pthreads,我正在用C学习线程,发现了下面的“Hello World”程序。当我使用pthread_join()在线程内和线程外打印pthread_value()的值时,两个线程返回的值完全不同 /****************************************************************************** * FILE: hello.c * DESCRIPTION: * A "hello world" Pthreads program. Demonstr
/******************************************************************************
* FILE: hello.c
* DESCRIPTION:
* A "hello world" Pthreads program. Demonstrates thread creation and
* termination.
* AUTHOR: Blaise Barney
* LAST REVISED: 08/09/11
******************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!, %ld\n", tid, pthread_self());
long a= pthread_self();
//pthread_exit(NULL);
long *p = &a;
return p;
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
void *status;
long t;
FILE* file = fopen("test.txt", "r");
for(t=0;t<NUM_THREADS;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for(t=0; t<NUM_THREADS;t++){
pthread_join(threads[t], &status);
printf("%ld\n",(long)status);
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
/******************************************************************************
*文件:hello.c
*说明:
*“hello world”Pthreads程序。演示线程创建和
*终止。
*作者:布莱斯·巴尼
*最后修订日期:08/09/11
******************************************************************************/
#包括
#包括
#包括
#定义NUM_线程5
void*PrintHello(void*threadid)
{
长tid;
tid=(长)线程ID;
printf(“你好,世界!是我,线程#%ld!,%ld\n”,tid,pthread_self());
长a=pthread_self();
//pthread_exit(NULL);
长*p=&a;
返回p;
}
int main(int argc,char*argv[])
{
pthread_t threads[NUM_threads];
int rc;
无效*状态;
长t;
FILE*FILE=fopen(“test.txt”、“r”);
for(t=0;tYourPrintHello()
函数返回局部变量的地址。在函数退出后尝试使用该地址是未定义的,任何事情都可能发生,从获取垃圾值到程序崩溃。另外,不要取消引用该地址以获取它指向的值(假设它仍然有效,但又不是),将地址强制转换为long并打印出地址本身。我怀疑这是您的意图。通常的方法应该是在线程中malloc足够的内存来保存其返回值,并返回该地址。然后在加入线程中,取消对该返回地址的引用以获得实际返回值,并释放该内存完成后。提示:当您返回局部变量的地址,然后尝试在代码的其他部分中取消引用它时,您认为会发生什么情况?谢谢您的提示。我意识到我的C基础知识不清楚,在使用线程之前花了7-8个小时。我现在知道哪里出了问题:)谢谢你的回答。这确实是一个愚蠢的问题,但我没有想到变量超出了范围。我完成了C的基础知识,以避免类似的情况