编写一个基本的多线程程序

标签 c multithreading pthreads

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

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

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

我应该如何继续修复段。错误?

最佳答案

您不能像在 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。

希望对您有所帮助。

关于编写一个基本的多线程程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15327430/

相关文章:

c - 当我编译 x264 时,出现错误 undefined reference to sync_fetch_and_add_4

c++ - C++中的线程池设计

java - 通过多个线程删除 java.util.Collection 元素

c - 请解释以下并行代码模板

c - 来自子进程的 pthread_create

c - 如何使用链接实现在c中的队列中插入元素

c - 如何更快地检查正则表达式列表

C 时间戳差异

c - 没有互斥量的 pthread_cond_wait 的潜在缺陷

linux - SCHED_FIFO 线程在 Linux 中被 SCHED_OTHER 线程抢占