에서 컴파일 된 아래 C 코드의 세분화 오류는 한 요리사가있는 tandoori 치킨 런치 뷔페 레스토랑과 여러 손님을 시뮬레이트합니다. 이는 단일 제작자/다중 소비자 문제와 유사합니다. 우리는 하나의 프로그램을 여러 스레드로 구현합니다. 각각의 프로그램에는 요리사 또는 손님이 있습니다. 공통 리소스를 여러 스레드와 동기화하는 문제를 해결할 수있는 하나의 동기화 도구 - 세마포어도 적용합니다. 이 프로젝트를 통해 다중 스레드 프로세스를 만드는 방법과 세마포를 사용하여 스레드를 동기화하는 방법을 배우게됩니다. 중요 섹션에있는linux
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
struct threadInfo
{
int id;
};
/* input variables */
int nofCustomers=4,item,nofChicken=3;
pthread_attr_t attr; /*Set of thread attributes*/
pthread_t chef_t,customer_t[100];
/* the semaphores */
sem_t full, empty;
void *chef(void *param); /* the producer thread */
void *customer(void *param); /* the consumer thread */
void initializeData()
{
/* Create the full semaphore and initialize to 0 */
sem_init(&full, 0, 0);
/* Create the empty semaphore and initialize to BUFFER_SIZE */
sem_init(&empty, 0, nofChicken);
/* Get the default attributes */
pthread_attr_init(&attr);
}
생산자
/* Producer Thread */
void *chef(void *param)
{
printf("Chef Starts Cooking\n");
while(1)
{
/* acquire the empty lock */
sem_wait(&empty);
if(insert_item())
{
fprintf(stderr, " Producer report error condition\n");
}
/* signal full */
sem_post(&full);
sleep(1);
}
}
소비자
/* Consumer Thread */
void *customer(void *param)
{
int toeat=1+rand()%4,ate=0,t=nofCustomers;
int *id=(int*)param;
printf("Guest %d arrives and wants to eat %d food\n", id, toeat);
while(1)
{
/* aquire the full lock */
sem_wait(&full);
if(remove_item())
{
fprintf(stderr, "Consumer report error condition\n");
}
else
{
ate++;
printf("Guest %d eats a tandoori chicken[%d/%d]\n", id,ate,toeat);
}
if(ate==toeat)
{
nofCustomers--;
printf("Guest %d finishes and exits\n",id);
}
if(nofCustomers==0)
{
printf("All guests finish eating and exit\n");
break ;
}
/* signal empty */
sem_post(&empty);
sleep(toeat);
}
}
INC 중요 섹션
을 IN/* Cook food */
int insert_item()
{
/* When the item is not full,cook food
increment the item*/
if(item <= nofChicken)
{
item++;
printf("Chef cooks one tandoori chicken.[%d/%d]\n",item,nofChicken);
return 0;
}
else
{ /* Error the items are full */
return -1;
}
}
12월 6,
/* Eat food */
int remove_item() {
/* When the items is/are cooked, eat the item
i.e.., decrement the item */
if(item > 0)
{
item--;
return 0;
}
else { /* Error no items */
return -1;
}
}
주요 함수 보브 코드
GDB에서 코드를 실행하여 segfault가 발생한 위치를 정확하게 찾을 수 있습니까? – Matt
gdb를 사용하여 정확한 seg 오류 라인을 찾으십시오. 하지만 우선'info-> id = i;'는'info'가 초기화되지 않은 포인터이기 때문에 seg fault를 일으킬 수 있습니다. 다른 에러는 모든 스레드에 동일한'info' 포인터를 전달하는 것을 포함합니다. 이는 각 스레드가'info-> id'의 무작위 값을 보게되며'main'은 스레드가 종료되기 전에 ('pthread_join') 완료되기를 기다리지 않습니다. – kaylum
스택 오버플로에 오신 것을 환영합니다! 사람들이 귀하의 질문에 답변하도록 돕기 위해 오류에 대해보다 구체적으로 설명해야합니다. 게시물을 편집하여 [mcve]를 실행하여 얻은 정확한 스택 추적을 통합하십시오 (가능한 경우 복사 + 붙여 넣기를 사용하여 전사 오류를 방지하십시오). –