3

我正在接近 C 中的 pthreads,并且我开始编写非常愚蠢的程序来掌握它们的窍门。我试图创建一个包含两个线程的程序,它们应该打印它们的名称,并且在它们终止执行时应该收集它们的状态。所以我的代码是:

//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;
}

我期望这样的输出:

Thread 1
Thread 2
Thread 1 - Return value: 0
Thread 2 - Return value: 0

Thread 1但我的问题是is的返回值733029576,但按预期Thread 2返回;0就像状态变量未初始化并包含垃圾一样。我错过了什么?

4

4 回答 4

5

您在输出中看到垃圾值的原因是局部void *status变量 ofstate_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);
}

进行此更改后,您的程序应该会产生您期望的输出。

请注意,status直接从返回state_your_name是调用的替代方法pthread_exit:您可以将该调用替换为return status.

于 2013-06-10T16:39:50.360 回答
2

您的代码state_your_name()不会初始化status它返回的内容,因此您会得到不确定的信息。你很不幸你得到的是零而不是垃圾。

于 2013-06-10T16:39:49.813 回答
2

您正在返回一个指向status在线程堆栈中定义的指针。线程退出后,该内存可能会消失。你不应该status在你的线程中声明。你最好还是在return 0里面做state_your_name()

请参阅如何从 C 中的线程返回值

于 2013-06-10T16:49:05.927 回答
0

要获得可预测的不同返回值,请尝试此操作

void *state_your_name(char *name) {
    //Declaration of the variable containing the return status
    void* status= (void *)(int)name[0];
    ....

这将返回名称第一个字母的 ascii 代码。

另外,我知道 pthread_join 的实现,将 void** 作为最后一个参数,所以

if (pthread_join(tid_2, &status)) {

会是正确的(你的铸造(void*)有点误导)

于 2013-06-10T16:44:23.823 回答