【问题标题】:Coding a basic multi-threaded program编写一个基本的多线程程序
【发布时间】:2013-03-10 20:49:58
【问题描述】:

我想创建 2 个线程,一个做最大值,一个给出在命令行中输入的数字列表的平均值。

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

void * thread1(int length, int array[] )
{

int ii = 0;
int smallest_value = INT_MAX;
        for (; ii < length; ++ii)
        {
                if (array[ii] < smallest_value)
                {
                        smallest_value = array[ii];
                }
        }
 printf("smallest is: %d\n", smallest_value);


}

void * thread2()
{

  printf("\n");

}

int main()
{
  int average;
  int min;
  int max;

  int how_many;
  int i;
  int status;
  pthread_t tid1,tid2;

  printf("How many numbers?: ");
  scanf("%d",&how_many);
  int ar[how_many];
  printf("Enter the list of numbers: ");
  for (i=0;i<how_many;i++){
  scanf("%d",&ar[i]);
  }

//for(i=0;i<how_many;i++)
//printf("%d\n",ar[i]);

        pthread_create(&tid1,NULL,thread1(how_many,ar),NULL);
        pthread_create(&tid2,NULL,thread2,NULL);
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
        return 0;
  exit(0);
}

我刚刚创建了第一个线程,即打印出最小值。编号,但我在编译时出现以下错误:

How many numbers?: 3
Enter the list of numbers: 1
2
3
Smallest: 1
Segmentation fault

我应该如何继续并修复该段。有错吗?

【问题讨论】:

  • array 是一个int。您可能的意思是使用 int *array 而不是 int array 声明函数。
  • @WilliamPursell 我现在降级到.c:58: error: expected expression before int .c:58: error: too few arguments to function thread1
  • void *thread1() 似乎返回一个值..
  • 我将第 57 行更改为 pthread_create(&amp;tid1,NULL,thread1( how_many, *ar),NULL); 现在它可以编译,但出现分段错误:\
  • pthread_create(&amp;tid1,NULL,thread1(how_many,ar),NULL); 在这里您调用函数thread1,而不是将函数指针发送到pthread_create。你需要这样做pthread_create(&amp;tid1,NULL,thread1, args);。我认为你只允许一个参数,所以你可以使用一个结构来包含两个参数。

标签: c multithreading pthreads


【解决方案1】:

您不能像在 pthread_create 中那样传递参数。

创建如下结构:

struct args_t
{
  int length;
  int * array;
}; 

然后用你的数组和长度初始化一个结构。

args_t *a = (args_t*)malloc(sizeof(args_t));
//initialize the array directly from your inputs

那就做吧

pthread_create(&tid1,NULL,thread1,(void*)a);

然后只需将参数转换回 args_t。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多