【发布时间】: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(&tid1,NULL,thread1( how_many, *ar),NULL);现在它可以编译,但出现分段错误:\ -
pthread_create(&tid1,NULL,thread1(how_many,ar),NULL);在这里您调用函数thread1,而不是将函数指针发送到pthread_create。你需要这样做pthread_create(&tid1,NULL,thread1, args);。我认为你只允许一个参数,所以你可以使用一个结构来包含两个参数。
标签: c multithreading pthreads