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

标签 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;
}

为什么我得到这样的值:

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.

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.

甚至:

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.

等等,当我期望得到:

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.

只有当我在 thread_create 之后放置 usleep(10) 时,我才会得到一些“正常”值。

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

最佳答案

您传递的是 for 正在更改的变量 (i) 的地址,因此您将受到调度程序的摆布。你应该只传递一份副本。作为一种廉价但不完全符合犹太洁食标准的方式:

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

/* ... */

int i = (int)a;

关于c - 多线程 C 程序中的错误线程 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14129675/

相关文章:

C8051F340 USB 设备数据传输硅实验室 IDE

java - 线程监听器通知

c++ - 使用 CMake 为 MonoDevelop 生成项目文件

c - 找出出现次数超过 N/3 的数

java - JNI 将 TreeMap 从 java 传递到 c

c# - 当我更新我的 ObservableCollection 时 GUI 卡住

c# - 在控制台应用程序中同步运行的任务

c++ - C 和 C++ 中使用的不同版本的 exec 是什么?

java - 使用异步方法从 java 类更新 UI

android - 在 LocalBroadcastManager 注册的 BroacastReceiver 的 onReceive() 在哪个线程运行?