linux

2016-10-12 3 views
2

에서 컴파일 된 아래 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; 
    } 
} 

주요 함수 보브 코드

+3

GDB에서 코드를 실행하여 segfault가 발생한 위치를 정확하게 찾을 수 있습니까? – Matt

+3

gdb를 사용하여 정확한 seg 오류 라인을 찾으십시오. 하지만 우선'info-> id = i;'는'info'가 초기화되지 않은 포인터이기 때문에 seg fault를 일으킬 수 있습니다. 다른 에러는 모든 스레드에 동일한'info' 포인터를 전달하는 것을 포함합니다. 이는 각 스레드가'info-> id'의 무작위 값을 보게되며'main'은 스레드가 종료되기 전에 ('pthread_join') 완료되기를 기다리지 않습니다. – kaylum

+0

스택 오버플로에 오신 것을 환영합니다! 사람들이 귀하의 질문에 답변하도록 돕기 위해 오류에 대해보다 구체적으로 설명해야합니다. 게시물을 편집하여 [mcve]를 실행하여 얻은 정확한 스택 추적을 통합하십시오 (가능한 경우 복사 + 붙여 넣기를 사용하여 전사 오류를 방지하십시오). –

답변

1

첫째, 수정이 컴파일 오류 :

g++ -std=c++17 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -O2 -Weffc++  39988874.cpp -o 39988874 
39988874.cpp: In function ‘void* chef(void*)’: 
39988874.cpp:43:25: error: ‘insert_item’ was not declared in this scope 
     if (insert_item()) { 
         ^
39988874.cpp:48:16: error: ‘sleep’ was not declared in this scope 
     sleep(1); 
       ^
39988874.cpp:36:18: warning: unused parameter ‘param’ [-Wunused-parameter] 
void *chef(void *param) 
        ^~~~~ 
39988874.cpp: In function ‘void* customer(void*)’: 
39988874.cpp:58:68: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int*’ [-Wformat=] 
    printf("Guest %d arrives and wants to eat %d food\n", id, toeat); 
                    ^
39988874.cpp:63:25: error: ‘remove_item’ was not declared in this scope 
     if (remove_item()) { 
         ^
39988874.cpp:67:77: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int*’ [-Wformat=] 
      printf("Guest %d eats a tandoori chicken[%d/%d]\n", id,ate,toeat); 
                      ^
39988874.cpp:71:54: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int*’ [-Wformat=] 
      printf("Guest %d finishes and exits\n",id); 
                ^
39988874.cpp:79:20: error: ‘sleep’ was not declared in this scope 
     sleep(toeat); 
        ^
39988874.cpp:56:32: warning: unused variable ‘t’ [-Wunused-variable] 
    int toeat=1+rand()%4,ate=0,t=nofCustomers; 
           ^
39988874.cpp:81:1: warning: no return statement in function returning non-void [-Wreturn-type] 
} 
^ 
<builtin>: recipe for target '39988874' failed 
make: *** [39988874] Error 1 

(힌트 : 당신은 sleep()에 대한 #include <unistd.h>이 필요합니다, 또한, 당신이 int id = ((threadInfo*)param)->id을 할 것입니다)

그 고정하는 데, 당신은 남아있을 것입니다 아주 분명

에 의해 발생

39988874.cpp: In function ‘int main()’: 
39988874.cpp:133:17: warning: ‘info’ may be used uninitialized in this function [-Wmaybe-uninitialized] 
     info->id=i; 
     ~~~~~~~~^~ 

struct threadInfo *info; 
/* ... */ 
for (i = 1; i <= nofCustomers; i++) { 
    info->id=i; 
} 

문제가 있습니다. info을 유효한 저장소로 지정해야합니다.

-1

코드를 컴파일 할 때 -Wall을 사용하고 (주의 깊게보고 이상 또는) 제거에

int main() 
{ 
    /* Loop counter */ 
    int i; 
    struct threadInfo *info; 

    //input (Havent written code for input includes nofChicken andnofCustomers 

    /* Initialize the app */ 
    initializeData(); 

    /* Create the producer thread */ 
    pthread_create(&chef_t,&attr,chef,NULL); 


    /* Create the consumer threads */ 
    for(i = 1; i <= nofCustomers; i++) 
{ 
    info->id=i; 
    pthread_create(&customer_t[i],&attr,customer,(void *)info); 
} 

return 0; 
} 

분할 오류 모든 경고.

+2

이것은 답변이 아닙니다. – unwind

+0

조금만 생각하면 더러운 코드로 인해 모든 세분화 오류가 발생하여 모든 경고 (위의 정확한 경고 참조) 또는 모든 세분화 오류가있는 벽을 사용하고 벽을 사용하도록 가르치는 것이 더 낫다는 것을 이해할 수 있습니다. 경고가 사용 중지되었습니다. – Rus

+0

감사합니다. 나는 그것에 대해 생각할 것입니다. 그래도 질문에 대한 답변이 아니며 더 많은 의견입니다. – unwind

관련 문제