2013-08-06 2 views
0

대기열에 항목을 추가하고 스레드가 항목을 대기열에 넣을 때 제거하려고합니다. 스택에서 뭔가를 가져온 다음 10 초 정도 기다린 다음 다시 시도하는 방식으로 진행했습니다. 임 스레드로 던지는 접근 방법을 모르겠다. 내가 PuTTy에 C를 사용하고있다. 나는 기능을 무시했다. 공간을 절약하기 위해 thme를 복사하지 않았습니다. delete() 함수는 첫 번째 스레드를 제거합니다. 스레드를 10 초 동안 일시 중지하려면 어떻게해야합니까? 절전 모드는 실제로 명령 창을 일시 중지합니다.C의 대기열에서 항목을 제거하는 스레드

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
//#include <conio.h> 

#define MAXQUEUE 100 

    struct queue 
    { 
     char name[256]; 
     struct queue *link; 
    }; 

void *thread_routine(void *arg) { 
    int tr; 
    while(tr!=0) { 
     sleep(10); 
     delete(); 
    } 

} 

struct queue *start=NULL; 

int i=0; 

void main() { 

    pthread_t thread1; 
    pthread_t thread2; 
    void *thread_result; 
    int status; 
    status = pthread_create(&thread1, NULL, thread_routine, NULL); 
    if (status != 0) { 
     printf ("thread create failed\n"); 
     exit(1); 
    } 
    /* wait for the thread to finish */ 

    status = pthread_join(thread1, &thread_result); 
    if (status != 0) { 
     printf ("thread join failed\n"); 
     exit(1); 
    } 
    printf ("child thread finished: result = %d\n", (int) thread_result); 

    int ch; 
    while(ch!=4) { 
     printf("\nSelect an option:\n"); 
     printf("1 to add an item to the queue\n"); 
     //printf("2 to delete an item from the queue\n"); 
     printf("3 to print the queue\n"); 
     printf("4 for Exit\n"); 
     scanf("%d",&ch); 
     switch(ch) { 
      case 1: 
       add(); 
       break; 
      case 2: 
       delete(); 
       break; 
      case 3: 
       print(); 
       break; 
      case 4: 

       break; 
      default: 
       printf("Incorrect option\n"); 
       break; 
     } 
    } 
} 
+0

'delete' 식별자는 예약 된 C++ 키워드이므로 사용하지 마십시오. –

답변

1

수면 실제로 명령 창을 일시 중지합니다.

스레드가 완료 될 때까지 기다렸다가 기다렸으므로 그 때문입니다. 스레드를 분리 된 상태로두고 아마도 옵션을 읽기위한 무한 루프를 만드십시오.

또한 mutex 및 조건 변수를 사용하여 새 항목이 삽입 될 때 스레드에 알리는 것이 좋습니다. "수면"방법을 사용하면 작동하지만 어쩌면 예상대로 항목을 삭제할 수 없습니다.

+0

분리 된 의미는 무엇입니까? 누군가 뮤텍스를 말했다. – DDukesterman

+0

마치 백그라운드에서 실행중인 것처럼 "분리됨"(따라서 main() 스레드와 결합되지 않았거나 단순히 데몬 인 것처럼) –

+0

스레드를 분리하려고하는 이유는 무엇입니까? 백그라운드에서 실행됩니까? – DDukesterman

0

아마도 sleep(). 대신 알람 신호를 사용할 수 있습니다. 신호 처리기를 설정하고 스레드가 차단하지 않았는지 확인하십시오.

+0

신호가 스레드와 교묘해서,이 접근법을 사용하지 않을 것입니다. –

관련 문제