繁体   English   中英

多线程但前几个线程被跳过

[英]Multithreading but first few threads are being skipped

已经几个小时了,我似乎无法理解这个问题。 构建此程序以从 1 到 10 计数。此程序的目标是使用多线程并根据它请求的线程数动态拆分数组。 问题是前 2 个线程被跳过,最后一个线程正在执行大部分过程。 我怀疑是 for 循环创建了线程。

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

typedef struct
{
    int *array;
    int batch;
    int start;
    int end;
} Parameter;

void *method(void *p)
{
    Parameter *param = (Parameter *)p;

    for (int i = param->start; i < param->end; i++)
    {
        printf("Start:%d\tEnd:%d\tIndex:%d\tValue:%d\n", param->start, param->end, i,param->array[i]);
        
    }
}

int main(int argc, char **argv)
{
    // Getting the user input
    int array_length = atoi(argv[1]);
    int batches = atoi(argv[2]);

    printf("User specified Array:%d\tBatch:%d\n", array_length, batches);

    // Creating an array
    int *array = (int *)calloc(array_length, sizeof(int));
    
    // Fill it up with some data
    for (int i = 0; i < array_length; i++)
    {
        array[i] = i;
    }

    // Determine the Batches
    int batch_size = array_length / batches;
    int remainder = array_length % batches;

    printf("%d\n", batch_size);
    printf("%d\n", remainder);

    int start = 0;
    int end = 0;
    int index =0;

    // List of parameters
    Parameter *param = (Parameter *)calloc(batches, sizeof(Parameter));
    pthread_t *threads = (pthread_t *)calloc(batches, sizeof(pthread_t));

    // Loop through each batch.
    for (int i = 0; i < batches; i++)
    {
        printf("\n\nBatch number -> %d\n", i);
        end = start + batch_size;
        if (remainder > 0)
        {
            remainder --;
            end ++;
        }

        // Fill the parameters
        param[i].array = array;
        param[i].end = end;
        param[i].start = start;
        param[i].batch = i;

        // Call the thread.
        pthread_create(threads + index, NULL, method, (void *)&param[i]);
        index++;
        start = end;
    }

    for (int i = 0; i < batches; i++)
    {
        pthread_join(threads[i], NULL);
    }

    free(param);
    free(threads);
    free(array);

    return 0;
}

一直在玩 for 循环的索引(第 57 行),因为我确定这是问题的原因。 得到了一些结果,但主要问题仍然存在。

代码按预期工作。 我是一个没有把 printf 放在空白 function 中的笨蛋。像这样:

void *method(void *p) {
Parameter *param = (Parameter *)p;
printf("\n\nBatch number -> %d\n", param->batch); //<-- moved from main method
for (int i = param->start; i < param->end; i++)
{
    printf("Start:%d\tEnd:%d\tIndex:%d\tValue:%d\n", param->start, param->end, i,param->array[i]);
    
} }

感谢您指出该程序有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM