C - 大量 posix 线程失控并且不再创建新线程

标签 c macos posix pthreads

我在类里面有一个作业要求我们使用 POSIX 线程并创建 n*(n-1)/2 个线程来处理 n 个元素的数据集。

您基本上可以将其视为经典的概率“握手”。

我知道对于大型数据集,它会使应用程序受 CPU 限制,最终它会花费大量时间进行上下文切换以致于毫无用处,但任务要求我们这样做。

但是,我创建所有线程的循环在一段时间后停止创建它们。

对于下面的代码,我将看到如下输出:

making thread
thread start
thread done
made thread 1944
making thread
thread start
thread done
made thread 1945
making thread
thread start
thread done
made thread 1946
making thread

一段时间后,我将不再看到“线程开始”和“线程完成”消息,而只会看到“创建线程,创建线程”消息。

这是创建线程的循环:

    int tCtr = 0;
    tArr = (pthread_t*)malloc(((numbers_read) * (numbers_read - 1)/2) * sizeof(pthread_t));
    for(i=0; i<numbers_read; i++){
        int j;
        for(j=i; j<numbers_read; j++){
            // n(n-1)/2
            if(i != j){
                printf("making thread\n");
                struct comparison_struct *data;
                data = (struct comparison_struct *)malloc(sizeof(struct comparison_struct));
                data->i_value = &numbers[i];
                data->j_value = &numbers[j];
                data->i_arr_entry = &wArr[i];
                data->j_arr_entry = &wArr[j];
                pthread_create(&tArr[tCtr], NULL, compare_thread, (void *)data);
                printf("made thread %d\n", tCtr);
                tCtr++;
            }
        }
    }
    for(i=0; i<tCtr; i++){
        pthread_join(tArr[i], NULL);
    }
    free(tArr);

这是包含线程代码的子例程:

void *compare_thread(void *vData) {
    printf("thread start\n");
    struct comparison_struct *data;
    data = (struct comparison_struct *)vData;
    if(*data->i_value <= *data->j_value){
        *data->i_arr_entry = 0;
    } else {
        *data->j_arr_entry = 0;
    }
    free(vData);
    printf("thread done\n");
    return NULL;
}

有人有什么想法吗?我是 pthreads 的新手,无法理解它。

我知道,如果我在 pthread_create 之后立即调用 pthread_join,应用程序会工作 - 但它会阻塞每个线程,我认为这会降低性能,因为实际上一次只会运行 2 个线程.

最佳答案

检查 pthread_create 的返回值,可能您正在达到资源限制。

 pthread_create() will fail if:

 [EAGAIN]           The system lacked the necessary resources to create
                    another thread, or the system-imposed limit on the
                    total number of threads in a process
                    [PTHREAD_THREADS_MAX] would be exceeded.

 [EINVAL]           The value specified by attr is invalid.

如果你达到了资源限制,你可以尝试创建一个加入其他线程的线程,创建一个工作队列并通过队列为每个线程分配工作,或者如果你控制了线程的资源限制系统尝试增加它。

关于C - 大量 posix 线程失控并且不再创建新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1837351/

相关文章:

c - 解释函数调用的分支覆盖率

python - Mac 上的 Visual Studio Code 中未出现 Matplotlib 图像

c++ - 有哪些有趣的 C/C++ 库可以玩?

linux - linux系统调用mmap(2)和posix mmap(3)函数有什么区别?

c++ - 如何在 Linux 中监视子进程状态

c - 在 gcc 编译器的标志中排除 "lib"前缀

c++ - 在没有 typedef 的情况下使用指向函数指针的指针?

C内联汇编帮助(digital mars c编译器)

swift - macOS 窗口叠加效果错误?

postgresql - 如何运行 postgres 命令 : could not identify current directory