c - C 中的线程加工错误?

标签 c multithreading

我编译了这段代码,它创建的第 99 个线程不断创建多个 99 号线程。相反,如果我插入 1-10 或较小的值,那么结果是相当正常的。

这是代码。

#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);
    usleep(10000);
    printf("The thread %d has finished.\n",i);
    pthread_mutex_unlock(&m);
    pthread_exit(NULL);

}

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

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

    }

    for (i=0;i<100;i++)
        pthread_join(thread[i],NULL);
    return 0;
}

我得到:

..../*Normal Results*/
The thread 99 has finished.
The thread 99 has finished.
The thread 99 has finished.
The thread 99 has finished.
The thread 99 has finished.
The thread 99 has finished.

为什么会发生这种情况?

最佳答案

您需要保留所有theadId

int indexes[PTHREAD_COUNT];

for (i=0;i<100;i++) {
    indexes[i] = i;
    pthread_create(&thread[i], &attr, test, &indexes[i]);
}

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

相关文章:

perl - 如何在 Perl 中的线程之间共享对象?

c - 我是否必须对 SQLITE 中的 argv 回调中的每个参数进行深度复制?

java - 主线程中的异常 - java.util.InputMismatchException

c# - 在编写多线程代码之前需要了解哪些重要的线程 API 调用?

c - 如何在文件末尾添加 2 字节 CRC

c# - IO 读写操作的 TPL 数据流实现中的内存问题

.net - 线程的身份

c - 如果没有必要的 header ,我的代码如何正确编译?

c - 如何获取前面没有 '-' 或 '--' 的参数

c - 将 Windows 套接字用于新进程 I/O