hau*_*d85 3 c pthreads return-value
我接近在C并行线程和我开始写作非常愚蠢的程序,让他们的窍门.我试图创建一个包含两个线程的程序,他们应该打印他们的名字,并在终止执行时收集他们的状态.所以我的代码是:
//Function declaration
void *state_your_name(char*);
//Function definition
//Passing a string as parameter for
//outputting the name of the thread
void *state_your_name(char *name) {
//Declaration of the variable containing the return status
void* status;
//Printing out the string
printf("%s\n", name);
//Exiting the thread and saving the return value
pthread_exit(status);
}
int main(void) {
pthread_t tid_1, tid_2;
void * status;
//Creating thread 1...
if (pthread_create(&tid_1, NULL, state_your_name, "Thread 1")) {
printf("Error creating thread 1");
exit(1);
}
//Creating thread 2...
if (pthread_create(&tid_2, NULL, state_your_name, "Thread 2")) {
printf("Error creating thread 2");
exit(1);
}
//Waiting for thread 1 to terminate and
//collecting the return value...
if (pthread_join(tid_1, (void *) &status)) {
printf("Error joining thread 1");
exit(1);
}
printf("Thread 1 - Return value: %d\n", (int)status );
//Waiting for thread 2 to terminate and
//collecting the return value...
if (pthread_join(tid_2, (void *) &status)) {
printf("Error joining thread 2");
exit(1);
}
printf("Thread 2 - Return value: %d\n", (int)status );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望输出像这样:
Thread 1
Thread 2
Thread 1 - Return value: 0
Thread 2 - Return value: 0
Run Code Online (Sandbox Code Playgroud)
但我的问题是返回值Thread 1是733029576,但Thread 2返回0的预测; 就像状态变量未初始化并包含垃圾一样.我错过了什么?
您在输出中看到垃圾值的原因是本地void *status变量state_your_name未初始化:
void *state_your_name(char *name) {
//Declaration of the variable containing the return status
void* status = NULL; // <<===== Add initialization here
//Printing out the string
printf("%s\n", name);
//Exiting the thread and saving the return value
pthread_exit(status);
}
Run Code Online (Sandbox Code Playgroud)
有了这个改变,你的程序应该产生你期望的输出.
请注意,status直接返回state_your_name是调用的替代方法pthread_exit:您可以使用替换该调用return status.