2015-06-08 4 views
0

Я пытаюсь решить проблему Продюсер-Потребитель, используя pthreads и буфер в виде вектора. Я хочу иметь возможность вводить количество потоков, которые я буду иметь от Производителей и Потребителей. Я получаю ошибку сегментации, как только я ввожу оба значения. Я компилирую код с помощью gcc и -lpthread, и я не получаю ошибку компиляции. Как исправить эту ошибку?Ошибка сегментации при создании количества потоков, введенных пользователем

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

#define MAX 1000//00   /* Numbers to produce */ 
#define SIZE 20     /* Size of Buffer  */ 

typedef struct { 
    int id; 
} parm; 

pthread_mutex_t the_mutex; 
pthread_cond_t condc, condp; 
int buffer[SIZE]; 
int c = 0; 

/* 
    @Function: printState 
    @In: integer i 
    @Out: none 

    @Description: Used to show the state of the buffer on a given state 
*/ 
void printState(int i){ 
    int j; 

    puts("Showing the state of the buffer: "); 
    printf("[ "); 
    for (j = 0; j < SIZE; j++){ 
     printf("%d ",buffer[j]); 
    } 
    printf("]\n"); 

} 

/* 
    @Function: producer 
    @In: void *ptr 
    @Out: none 

    @Description: Call a producer on the process 
*/ 

void* producer(void *ptr){ 
    int i; 

    for (i = 1; i <= MAX; i++){ 
     printf("calling producer\n");// on position %d.\n",c+1); 
     pthread_mutex_lock(&the_mutex); /* protect the buffer */ 

     if(c == SIZE){ /* If the buffer is full, wait */ 
      puts("The buffer is full. Waiting."); 
      pthread_cond_wait(&condp, &the_mutex); 
     } 

     buffer[c] = 1; 
     c++; 

     printf("There are %d occupied positions on the buffer.\n", c); 
     pthread_cond_signal(&condc); /* Wake up the consumer */ 
     pthread_mutex_unlock(&the_mutex); /* Release the buffer */ 

     //if(i == MAX/2){ 
     // printState(i); 
     //} 

    } 
    pthread_exit(0); 
} 

/* 
    @Function: consumer 
    @In: void *ptr 
    @Out: none 

    @Description: Call a consumer on the process 
*/ 
void* consumer(void *ptr) { 
    int i, j; 

    for (i = 1; i <= MAX; i++){ 
     printf("calling consumer\n");// on position %d\n", c+1);  
     pthread_mutex_lock(&the_mutex); /* protect the buffer */ 
     if (c == 0){ /* If there is nothing in the buffer, wait */ 
      puts("Buffer is empty. Waiting."); 
      pthread_cond_wait(&condc, &the_mutex); 
     } 
     buffer[c] = 0; 
     c--; 
     printf("There are %d occupied positions on the buffer.\n", c); 

     pthread_cond_signal(&condp); /* wake up consumer */ 
     pthread_mutex_unlock(&the_mutex); /* release the buffer */ 

     //if(i == MAX){ 
     // printState(i); 
     //} 

    } 
    pthread_exit(0); 
} 

/* 
    @Function: main 
    @In: integer argc and character **argv 
    @Out: none 

    @Description: Main function of the algorithm 
*/ 
int main(int argc, char **argv){ 
    pthread_t *pro_threads, *con_threads; 
    pthread_attr_t pro_pthread_custom_attr, con_pthread_custom_attr; 
    int i, M, N; 
    parm *p_pro, *p_con; 

    puts("Please, enter the number of producer threads:"); 
    scanf("%d",&N); 

    puts("Please, enter the number of consumer threads:"); 
    scanf("%d",&M); 

    for(i=0;i<SIZE;i++){ 
     buffer[i] = 0; 
    } 

    // Allocate space for the threads 

    pro_threads=(pthread_t *)malloc(N*sizeof(*pro_threads)); 
    pthread_attr_init(&pro_pthread_custom_attr); 
    con_threads=(pthread_t *)malloc(M*sizeof(*con_threads)); 
    pthread_attr_init(&con_pthread_custom_attr); 

    // Initialize the mutex and condition variables 

    pthread_mutex_init(&the_mutex, NULL); /* Initialize the mutex */ 
    pthread_cond_init(&condc, NULL); /* Initialize the consumer condition variable */ 
    pthread_cond_init(&condp, NULL); /* Initialize the producer condition variable */ 

    // Create the threads 

    for (i=0; i<N; i++){ 
     p_pro[i].id=i; 
     pthread_create(&pro_threads[i], &pro_pthread_custom_attr, producer, (void *)(p_pro+i)); 
    } 

    for (i=0; i<M; i++){ 
     p_con[i].id=i; 
     pthread_create(&con_threads[i], &con_pthread_custom_attr, consumer, (void *)(p_con+i)); 
    } 

    // Wait for the threads to finish. 
    // Otherwise main might run to the end 
    // and kill the entire process when it exits. 

    for (i=0; i<N; i++){ 

     pthread_join(pro_threads[i], NULL); 
    } 

    for (i=0; i<M; i++){ 

     pthread_join(con_threads[i], NULL); 
    } 

    // Cleanup -- would happen automatically at the end of program 

    pthread_mutex_destroy(&the_mutex); /* Free up the_mutex */ 
    pthread_cond_destroy(&condc); /* Free up the consumer condition variable */ 
    pthread_cond_destroy(&condp); /* Free up the producer condition variable */ 
    free(p_pro); 
    free(p_con); 
    return 0; 
} 
+0

Вы должны будете использовать 'gdb' и попытаться со случайной нитью, чтобы увидеть, если проблема происходит, что делает его очень жесткие Такс, так что вы можете попробовать, чтобы понять это из кода. –

+1

[Отладка рекомендаций для небольших программ] (http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). –

+0

@i_am_jorf, даже если мне больно признаться, я прекрасный пример человека, которому нужно было прочитать эту статью. Благодарю. o/ –

ответ

0

Это университетский курс или еще что-то?

Проблема сообщается компилятором (gcc), если только вы просите его включить предупреждения. Тот, кто «учит» вас, должен был сказать вам это.

meh.c: В функции 'printState': meh.c: 25: 21: предупреждение: не используется параметр 'я' [-Wunused-параметр] недействительным printState (INT I) { ^ meh.c : В функции «производитель»: meh.c: 47: 22: предупреждение: неиспользуемый параметр «ptr» [-Wunused-parameter] void * производитель (void ptr) { ^ meh.c: В функции «потребитель»: meh.c: 85: 12: warning: unused variable 'j' [-Wunused-variable] int i, j; ^ meh.c: 84: 22: warning: unused parameter 'ptr' [-Wunused-parameter] void потребитель (void * ptr) { ^ meh.c: В функции 'main': meh.c: 118: 14: предупреждение: неиспользуемый параметр 'argc' [-Wunused-parameter] int main (int argc, char ** argv) { ^ meh.c: 118: 27: предупреждение: неиспользуемый параметр 'argv' [-Wunused-parameter ] int main (int argc, char ** argv) { ^ meh.c: 150: 14: warning: 'p_pro' может использоваться неинициализированным в этой функции [-Wmaybe-uninitialized] p_pro [i] .id = i ; ^ meh.c: 155: 14: warning: 'p_con' может использоваться неинициализированным в этой функции [-Wmaybe-uninitialized] p_con [i] .id = i;

Однако проблема тривиально диагностирована даже при стандартных методах, таких как нанесение printfs здесь и там, чтобы сузить место сбоя.

Как таковой, я смущен в отношении того, что было проблемой при выяснении того, что не так.

В коде есть некоторые тривиальные ошибки, из-за которых он не работает даже при фиксированном segfault. Я опускаю их, поскольку они имеют дело с общей проблемой.

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

#define MAX 1000//00   /* Numbers to produce */ 
#define SIZE 20     /* Size of Buffer  */ 

typedef struct { 
    int id; 
} parm; 

pthread_mutex_t the_mutex; 
pthread_cond_t condc, condp; 
int buffer[SIZE]; 
int c = 0; 

Это уже 0. Ужасное не описательное имя для глобальной переменной. //---------------------------------------------------------------------------- -

/* @Function: printState @in: целое число, я @out: нет

@Description: Used to show the state of the buffer on a given state 
*/ 
void printState(int i){ 

Неиспользованный плохо названный аргумент.

int j; 

Идиома должна использовать «i» в качестве индекса цикла.

puts("Showing the state of the buffer: "); 
    printf("[ "); 
    for (j = 0; j < SIZE; j++){ 
     printf("%d ",buffer[j]); 
    } 
    printf("]\n"); 

} 
//----------------------------------------------------------------------------- 

//----------------------------------------------------------------------------- 
/* 
    @Function: producer 
    @In: void *ptr 
    @Out: none 

    @Description: Call a producer on the process 
*/ 

void* producer(void *ptr){ 

Непосредственное размещение «*». Поставить его с типом имя ужасное.

int i; 

    for (i = 1; i <= MAX; i++){ 

«i» не используется в цикле, поэтому фактическое значение не имеет значения. Идиома должна идти от 0 до < MAX.

 printf("calling producer\n");// on position %d.\n",c+1); 
     pthread_mutex_lock(&the_mutex); /* protect the buffer */ 

     if(c == SIZE){ /* If the buffer is full, wait */ 
      puts("The buffer is full. Waiting."); 
      pthread_cond_wait(&condp, &the_mutex); 
     } 

     buffer[c] = 1; 
     c++; 

     printf("There are %d occupied positions on the buffer.\n", c); 
     pthread_cond_signal(&condc); /* Wake up the consumer */ 
     pthread_mutex_unlock(&the_mutex); /* Release the buffer */ 

     //if(i == MAX/2){ 
     // printState(i); 
     //} 

    } 
    pthread_exit(0); 
} 
//----------------------------------------------------------------------------- 


//----------------------------------------------------------------------------- 
/* 
    @Function: consumer 
    @In: void *ptr 
    @Out: none 

    @Description: Call a consumer on the process 
*/ 
void* consumer(void *ptr) { 
    int i, j; 

    for (i = 1; i <= MAX; i++){ 
     printf("calling consumer\n");// on position %d\n", c+1);  
     pthread_mutex_lock(&the_mutex); /* protect the buffer */ 
     if (c == 0){ /* If there is nothing in the buffer, wait */ 
      puts("Buffer is empty. Waiting."); 
      pthread_cond_wait(&condc, &the_mutex); 
     } 
     buffer[c] = 0; 
     c--; 
     printf("There are %d occupied positions on the buffer.\n", c); 

     pthread_cond_signal(&condp); /* wake up consumer */ 
     pthread_mutex_unlock(&the_mutex); /* release the buffer */ 

     //if(i == MAX){ 
     // printState(i); 
     //} 

    } 
    pthread_exit(0); 
} 
//----------------------------------------------------------------------------- 

//----------------------------------------------------------------------------- 
/* 
    @Function: main 
    @In: integer argc and character **argv 
    @Out: none 

    @Description: Main function of the algorithm 
*/ 
int main(int argc, char **argv){ 
    pthread_t *pro_threads, *con_threads; 
    pthread_attr_t pro_pthread_custom_attr, con_pthread_custom_attr; 
    int i, M, N; 

Полностью капитализированные имена идиоматически используются с макросами. Ужасные не описательные имена.

parm *p_pro, *p_con; 

    puts("Please, enter the number of producer threads:"); 
    scanf("%d",&N); 

    puts("Please, enter the number of consumer threads:"); 
    scanf("%d",&M); 

Я не знаю, кто и почему рекомендует, чтобы новички использовали это. Вместо этого используйте argv.

for(i=0;i<SIZE;i++){ 
     buffer[i] = 0; 
    } 

Этот буфер уже обнулен. Ужасный интервал несовместим с тем, который использовался ранее.

// Allocate space for the threads 

    pro_threads=(pthread_t *)malloc(N*sizeof(*pro_threads)); 

Кастинг malloc активно вреден.

pthread_attr_init(&pro_pthread_custom_attr); 
    con_threads=(pthread_t *)malloc(M*sizeof(*con_threads)); 
    pthread_attr_init(&con_pthread_custom_attr); 

    // Initialize the mutex and condition variables 

    pthread_mutex_init(&the_mutex, NULL); /* Initialize the mutex */ 
    pthread_cond_init(&condc, NULL); /* Initialize the consumer condition variable */ 
    pthread_cond_init(&condp, NULL); /* Initialize the producer condition variable */ 

    // Create the threads 

    for (i=0; i<N; i++){ 
     p_pro[i].id=i; 

p_pro не инициализирован.

 pthread_create(&pro_threads[i], &pro_pthread_custom_attr, producer, (void *)(p_pro+i)); 

Отсутствует проверка ошибок. Непоследовательное использование p_pro.

} 

    for (i=0; i<M; i++){ 
     p_con[i].id=i; 
     pthread_create(&con_threads[i], &con_pthread_custom_attr, consumer, (void *)(p_con+i)); 
    } 

    // Wait for the threads to finish. 
    // Otherwise main might run to the end 
    // and kill the entire process when it exits. 

    for (i=0; i<N; i++){ 

     pthread_join(pro_threads[i], NULL); 
    } 

    for (i=0; i<M; i++){ 

     pthread_join(con_threads[i], NULL); 
    } 

    // Cleanup -- would happen automatically at the end of program 

    pthread_mutex_destroy(&the_mutex); /* Free up the_mutex */ 
    pthread_cond_destroy(&condc); /* Free up the consumer condition variable */ 
    pthread_cond_destroy(&condp); /* Free up the producer condition variable */ 
    free(p_pro); 
    free(p_con); 
    return 0; 
} 
+0

Это все, что вы нашли? :) –

+0

, поэтому причина отказа в том, что p_pro не инициализирован, все остальные комментарии связаны стилем? – pm100

+0

Я забыл добавить следующее в верхней части алгоритма: /* * Решение Producer потребителей Проблема * Использование Ptheads мьютекс и переменные условия * От Таненбаум, Операционные системы, Современные, 3-е издание. */ Итак, эй, это вина Танембаума за много чего. Но да, я вижу ошибку, которую вы указали на Майн. И я благодарю вас за это. Собираюсь проверить это здесь, а затем прокомментировать результаты. –

Смежные вопросы