多线程C程序中的线程ID错误?

Bil*_*das 2 c multithreading

我是C语言中的多线程新手,我有这个问题.我写了以下代码:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;
pthread_attr_t attr;

void* test(void *a)
{
    int i=*((int *)a);
    printf("The thread %d has started.\n",i);
    pthread_mutex_lock(&m);
    sleep(1);
    printf("The thread %d has finished.\n",i);
    pthread_mutex_unlock(&m);
    pthread_exit(NULL);

}

int main()
{
    int i=0;
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
    pthread_t thread[5];

    for (i=0;i<5;i++)
        pthread_create(&thread[i],&attr,test,&i);

    for (i=0;i<5;i++)
        pthread_join(thread[i],NULL);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么我会得到如下值:

The thread 0 has started.
The thread 0 has started.
The thread 5 has started.
The thread 5 has started.
The thread 0 has started.
The thread 0 has finished.
The thread 0 has finished.
The thread 5 has finished.
The thread 5 has finished.
The thread 0 has finished.
Run Code Online (Sandbox Code Playgroud)

要么

The thread 1 has started.
The thread 2 has started.
The thread 5 has started.
The thread 4 has started.
The thread 0 has started.
The thread 1 has finished.
The thread 2 has finished.
The thread 5 has finished.
The thread 4 has finished.
The thread 0 has finished.
Run Code Online (Sandbox Code Playgroud)

甚至:

The thread 0 has started.
The thread 0 has started.
The thread 0 has started.
The thread 0 has started.
The thread 0 has started.
The thread 0 has finished.
The thread 0 has finished.
The thread 0 has finished.
The thread 0 has finished.
The thread 0 has finished.
Run Code Online (Sandbox Code Playgroud)

等,当我期望得到:

The thread 0 has started.
The thread 1 has started.
The thread 2 has started.
The thread 3 has started.
The thread 4 has started.
The thread 0 has finished.
The thread 1 has finished.
The thread 2 has finished.
The thread 3 has finished.
The thread 4 has finished.
Run Code Online (Sandbox Code Playgroud)

只有当我放下usleep(10)thread_create才会得到一些"正常"值.

我在Unix上的Code :: Blocks中编译并运行了这段代码.

cni*_*tar 5

您正在传递变量for(i)的变量地址,因此您将受调度程序的支配.你应该传递一份副本.作为一种廉价,而不是完全犹太的方式:

pthread_create(&thread[i],&attr,test, (void*)i);

/* ... */

int i = (int)a;
Run Code Online (Sandbox Code Playgroud)