编写基本的多线程程序

时间:2021-02-13 21:02:44

I want to create 2 threads, one does the max and one gives the average of a list of numbers entered in the command line.

我想创建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);
}

I just made the first thread, which is to print out the min. number, but I have the following errors when compiling:

我刚刚制作了第一个线程,即打印出min。编号,但编译时出现以下错误:

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

How should I go on and fix the seg. fault?

我该如何继续修复seg。故障?

1 个解决方案

#1


0  

You can't pass arguments like you're trying to in pthread_create.

你无法传递像你在pthread_create中尝试的参数。

Create a structure like:

创建一个结构,如:

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

then initialize a structure with your array and length.

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

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

Then do

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

Then just cast the argument back to an args_t.

然后将参数强制转换为args_t。

Hope that helps.

希望有所帮助。

#1


0  

You can't pass arguments like you're trying to in pthread_create.

你无法传递像你在pthread_create中尝试的参数。

Create a structure like:

创建一个结构,如:

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

then initialize a structure with your array and length.

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

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

Then do

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

Then just cast the argument back to an args_t.

然后将参数强制转换为args_t。

Hope that helps.

希望有所帮助。