代码分段错误(核心转储)pthread创建[关闭]

问题描述 投票:0回答:1

我是线程编程的新手,并试图学习如何创建线程。我创建了一个线程并传递了参数,但在执行过程中,我遇到了一个分段错误。使用地址空间时可能出现故障。代码如下。

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

struct task_spec_struct 
{ 
    char task_type;
    int period,r_min,r_max;
}s1;

int gen_rand(int a, int b) 
{ 
    srand(time(NULL));
     int x = a+(rand()%(b-a));
      return x;
}

//task body to utilize CPU to perform computations

void* periodic_task(void* arg)
{
   struct task_spec_struct *arg_struct = (struct task_spec_struct*) arg;


  int rand_num = gen_rand(arg_struct->r_min, arg_struct->r_max);
  while(1)

   {
  int i, j=0;
  for(i=0; i<rand_num; i++)
  {
     j=j+i;
     }
  usleep((arg_struct->period)*1000);
  printf("Executing thread1");
  }
  pthread_exit(0);
}


int main(int argc, char **argv)
{
  int num_args = argc-1;
// Creating pthread for periodic task ( runs Thread function to run periodically)
  printf("Give task with specifications");
  s1.task_type= 'P';
  s1.period= 300;
  s1.r_min= 400;
  s1.r_max= 500;

 pthread_t tid;
 pthread_attr_t attr;
 pthread_attr_init(&attr);
 pthread_create(tid, &attr, periodic_task, &s1);



  pthread_join(tid, NULL);

}

请尽可能提供任何反馈。

c linux pthreads
1个回答
2
投票

pthread_t是用于唯一标识线程的数据类型。这是因为它作为指针传递而不是作为pthread_create()的值传递是因为它由pthread_create()填充并返回,以供应用程序在需要线程标识符的函数调用中使用。看到这个reference

这就是为什么你的电话应该如下:

pthread_create(&tid, &attr, periodic_task, &s1);
© www.soinside.com 2019 - 2024. All rights reserved.