pthread_create segfault(缓冲读卡器示例)

时间:2016-03-08 05:20:00

标签: c linux multithreading

我已经为我的OS类编写了一个简单的缓冲读者问题解决方案,但是在一些成功的生产者线程之后,我得到了一个segfault。输出,bt和代码如下:

输出:

Producer 1 exiting
Producer 2 exiting
Producer 3 exiting
Segmentation fault (core dumped)

线程BT(使用GDB thread apply all where):

Thread 2 (Thread 0x7ffff77f6700 (LWP 8310)):
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff7bc4182 in start_thread (arg=0x7ffff77f6700)
    at pthread_create.c:312
#2  0x00007ffff78f147d in clone ()
    at ../sysdeps/unix/sysv/linux/x86_64/clone.S:111

Thread 1 (Thread 0x7ffff7fd3740 (LWP 8299)):
#0  0x00007ffff78eba27 in mprotect () at ../sysdeps/unix/syscall-template.S:81
#1  0x00007ffff7bc4f21 in allocate_stack (stack=<synthetic pointer>, 
    pdp=<synthetic pointer>, attr=0x7fffffffde20) at allocatestack.c:650
#2  __pthread_create_2_1 (newthread=0x6021e0, attr=<optimized out>, 
    start_routine=0x0, arg=0x0) at pthread_create.c:500
#3  0x00000000004009cf in start_producer () at 6-2.c:75
#4  0x00000000004007e9 in main () at 6-2.c:29

代码:

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

void init();
void start_producer();
void start_consumer();
void *produce();
void *comsume();


int buffer_count;
int max_buffers;
int producer_count;
sem_t *mutex;
sem_t *full;
sem_t *empty;

int main() {
  init();

  int i = 0;

  for(i = 0; i < 3; i++) {
      start_producer();
  }

  for(i = 0; i < 3; i++) {
    start_consumer();
  }
  return 0;
}

void init() {
  buffer_count = 0;
  max_buffers = 3;
  producer_count = 0;
  mutex = malloc(sizeof(sem_t));
  full = malloc(sizeof(sem_t));
  empty = malloc(sizeof(sem_t));

  sem_init(mutex, 0, 1);
  sem_init(full, 0, 0);
  sem_init(empty, 0, max_buffers);
}

void *produce() {
  sem_wait(empty);
  sem_wait(mutex);
  producer_count++;
  printf("Producer %d exiting\n", producer_count);
  sem_post(full);
  sem_post(mutex);
  return 0;
}

void *consume() {
  sem_wait(full);
  sem_wait(mutex);
  printf("Consuming produced value: %d\n", producer_count);
  producer_count--;
  sem_post(empty);
  sem_post(full);
  return 0;
}

void start_producer() {
  pthread_t *thread = malloc(sizeof(pthread_t));
  if(pthread_create(thread, NULL, produce(), NULL) != 0)
    printf("\tError creating producer thread.\n");
}

void start_consumer() {
  pthread_t *thread = malloc(sizeof(pthread_t));
  if(pthread_create(thread, NULL, consume(), NULL) != 0)
    printf("\tError creating consumer thread.\n");
}

我知道这可能是一个新问题。我很难调试这个。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您将NULL传递给pthread_create的第三个参数,它很有可能导致分段错误。

尝试这些行

if(pthread_create(thread, NULL, produce, NULL) != 0)
if(pthread_create(thread, NULL, consume, NULL) != 0)

而不是

if(pthread_create(thread, NULL, produce(), NULL) != 0)
if(pthread_create(thread, NULL, consume(), NULL) != 0)

(不要拨打produceconsume,改为传递指针