Я пытаюсь решить проблему Продюсер-Потребитель, используя 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;
}
Вы должны будете использовать 'gdb' и попытаться со случайной нитью, чтобы увидеть, если проблема происходит, что делает его очень жесткие Такс, так что вы можете попробовать, чтобы понять это из кода. –
[Отладка рекомендаций для небольших программ] (http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). –
@i_am_jorf, даже если мне больно признаться, я прекрасный пример человека, которому нужно было прочитать эту статью. Благодарю. o/ –