Core Dumped - 尝试使用Threads打印Min

时间:2017-09-20 01:25:08

标签: c multithreading

我正在尝试使用线程打印出我在以下代码中为静态数组执行此操作的数组中的最小数字:

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

int length = 5;
int nums[5] = {93, 12, 54, 72, 68};
int r_min;

void *myMin(void *param) {
    int i;

    r_min = nums[0];
    for(i = 0; i < length; ++i) {
        if(r_min > nums[i]) r_min = nums[i];
    }
    pthread_exit(0);
}

int main(int argc, char** argv) {
    pthread_t tid;
    pthread_create(&tid, 0, myMin, NULL);
    pthread_join(tid, NULL);
    printf("Min = %d\n", r_min);
    return 0;
}

这在我的例子中正确打印出“12”,这是正确的。我现在试图从命令行而不是硬编码数组中实现数字输入并打印出正确的响应。我的新代码如下:

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

int length = 5;
int nums[5] = {93, 12, 54, 72, 68};
int r_min;

void *myMin(void *param) {
    int i;

    r_min = nums[0];
    for(i = 0; i < length; ++i) {
        if(r_min > nums[i]) r_min = nums[i];
    }
    pthread_exit(0);
}

void* myMin2(void *param) {
    char** argv;
    int i, j;
    // printf("Test");
    argv = param;
    for(i = 0; i < length; ++i){
        printf("%s\n", argv[i]);

        if(i > 0){
            j = atoi(argv[1]);
            printf(" %d\n", j);
        }
    }

    pthread_exit(0);
}

int main(int argc, char** argv) {
    pthread_t tid;
    length = argc;
    pthread_create(&tid, 0, myMin2, NULL);
    pthread_join(tid, NULL);
    printf("Min = %d\n", r_min);
    return 0;
}

我设置的长度等于添加的参数数量(我可以/将在那里添加-1,因为调用执行命令计为1)。当我调用我的新Min2函数时,我只是遇到了分段错误(核心转储),我不完全确定原因。我对C语言很陌生,所以这对我来说都很混乱!谢谢你的协助! :)

1 个答案:

答案 0 :(得分:1)

您将myMin2作为参数传递给argv。您需要改为pthread_create(&tid, 0, myMin2, argv);

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net461;netcoreapp2.0</TargetFrameworks>