我的循环在多线程中不正确 运行

My loop doesnt run properly in multi-threading

我尝试写一个多线程程序,遇到了一些问题

在我 运行 main.c 之后,我得到

i: 0
new thread 0
new thread 1
i: 1
i: 1

//main.c
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>
void* routine(void* arg)
{
    int id = (intptr_t) arg;
    printf("new thread %d\n", id);
    pthread_exit((void*)(intptr_t) id);
}
int main()
{
    pthread_t t[2];
    int i;
    for(i=0; i<2; i++)
    {
        int ret = pthread_create (&t[i], NULL, &routine,  (void *)(intptr_t) i);
        if(ret != 0) {
            printf("Error: pthread_create() failed\n");
            return -1;
        }
    }
    int id;
    /////////here
    for(i=0; i<2; i++)
    {
        printf("i: %d\n",i);
        pthread_join(t[i], (void **)&id);
    }
    /////////here
    pthread_exit(NULL);
}

我的问题是

感谢您花时间阅读我的问题。

首先添加更多调试日志:

int id;
for(i=0; i<2; i++)
{
    printf("i: %d\n",i);
    pthread_join(t[i], (void **)&id);
    printf("id[%d]: %d\n", i, id);
}

重新运行并记住输出。

然后改成这样

int id;
for(i=0; i<2; i++)
{
    void * pv;   
    printf("i: %d\n",i);
    pthread_join(t[i], &pv); /* Add error checking here! */
    id = (intptr_t) pv;
    printf("id: %d\n", id);
}

重新运行并与之前的版本进行比较。


根据经验:

如果面对看似需要在 C(而非 C++)中进行转换,请务必三思,因为只有 非常非常非常罕见 需要在 C 中进行转换的情况而不仅仅是通过使编译器静音来隐藏编程错误。