所以我试图让这个程序用信号量工作。 终于摆脱了所有的错误,现在它给我一个核心转储问题? 试图找出我做错了什么,整个上午一直在工作,似乎无法找到问题。
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define BUFF_SIZE 20
char buffer[BUFF_SIZE];
int nextIn = 0;
int nextOut = 0;
//char sem_name1[] = "mutex";
//char sem_name2[] = "empty_slots";
//char sem_name3[] = "full_slots";
sem_t *empty_slots;
sem_t *full_slots;
sem_t *mutex;
typedef struct {
char buffer[BUFF_SIZE];
int nextIn;
int nextOut;
} shared_data;
void Put(char item){
sem_wait(empty_slots);
sem_wait(mutex);
buffer[nextIn] = item;
nextIn = (nextIn + 1) % BUFF_SIZE;
sem_post(mutex);
printf("Producing %c ...\n", item);
sem_post(full_slots);
}
void * Producer(){
int i;
for(i = 0; i < 15; i++){
sleep(rand()%6);
Put((char)('A'+ i % 26));
}
}
void Get(char item){
sem_wait(full_slots);
sem_wait(mutex);
item= buffer[nextOut];
nextOut = (nextOut + 1) % BUFF_SIZE;
sem_post(mutex);
printf("Consuming %c ...\n", item);
sem_post(empty_slots);
}
void * Consumer(){
int i;
char item;
for(i = 0; i < 15; i++){
sleep(rand()%6);
Get(item);
}
}
void main(){
sem_init(empty_slots, 0, 1);
sem_init(full_slots, 0, BUFF_SIZE);
sem_init(mutex, 0, 1);
/* Initialize semaphores */
pthread_t pid, cid;
pthread_create(&pid, NULL, Producer, NULL);
pthread_create(&cid, NULL, Consumer, NULL);
// create more consumer & producer threads.
pthread_join(pid, NULL);
pthread_join(cid, NULL);
}
当我使用gdb时,我收到错误
(gdb)
Id Target Id Frame
* 1 Thread 0xb7de8700 (LWP 3567) "labp2" __new_sem_init (sem=0x0, pshared=0, value=1)
at sem_init.c:60
(gdb)