2016-03-08 112 views
-1

我已經寫了一個簡單的解決方案,爲我的操作系統類緩衝閱讀器問題,但一些成功的生產者線程後,我得到一個segfault。輸出,BT和下面的代碼:pthread_create段錯誤(緩衝讀取器示例)

輸出:

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"); 
} 

我明白,這可能是一個新問題。我很難調試這個。在此先感謝您的幫助。

回答

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,通過他們的指針代替)