2012-04-12 5 views
1
gcc (GCC) 4.6.3 
valgrind-3.6.1 

송수신을 위해 2 개의 다른 스레드에서 일부 메시지를 보내고받는 응용 프로그램을 만들었습니다. pthreads를 사용하여 잠금을위한 변수 및 뮤텍스를 조건 지정합니다.pthread 취소 또는 삭제

그러나 보낸 사람은 메시지를 보낸 다음받는 사람에게 메시지를 보내고 처리하도록 신호를 보냅니다. while 루프에서이 작업을 수행합니다.

그러나 Ctrl-c를 사용하고 간섭을 처리하여 응용 프로그램을 종료하려면 문제가 발생합니다. 메시지가 보내지지 않으면 수신자는 수신 대기중인 while 루프에 갇혀있다.

메인 스레드는 수신자가 마치는 것을 기다리고 블록을 호출하고 차단합니다. 하지만 그것은 기다리는대로하지 않습니다 pthread_cond_wait.

pthread_cancel 또는 pthread_kill을 사용하려고 생각했습니다. 하지만 스레드를 정상적으로 종료 할 수 없기 때문에 그렇게하지 않습니다.

의견을 보내 주셔서 감사합니다.

주요 기능

void main(void) 
    { 
     /* Do some stuff here */ 

    /* Start thread that will send a message */ 
    if(pthread_create(&thread_recv_id, &thread_attr, thread_recv_fd, NULL) == -1) { 
     fprintf(stderr, "Failed to create thread, reason [ %s ]", 
      strerror(errno)); 
      break; 
     } 
     printf("Start listening for receiving data'\n"); 

     /* Start thread to receive messages */ 
     if(pthread_create(&thread_send_id, &thread_attr, thread_send_fd, NULL) == -1) { 
      fprintf(stderr, "Failed to create thread for receiving, reason [ %s ]", 
        strerror(errno)); 
      break; 
     } 

    /* Clean up threading properties */ 
    pthread_join(thread_send_id, NULL); 
    pthread_join(thread_recv_id, NULL); <---- blocking here waiting for the recv thread to finish 

    pthread_mutex_destroy(&mutex_queue); 
    pthread_cond_destroy(&cond_queue); 

    return 0; 
} 

발신자 스레드

void *thread_send_fd() 
{ 
     pthread_mutex_lock(&mutex_queue); 
     if(send_fd((int)fd) == FALSE) { 
      /* Just continue to send another item */ 
      continue; 
     } 
     /* Signal the waiting thread to remove the item that has been sent */ 
     pthread_cond_signal(&cond_queue); 

     pthread_mutex_unlock(&mutex_queue); 
} 

수신기 스레드

void *thread_recv_fd() 
{ 
    while(is_receiving()) { 
     pthread_mutex_lock(&mutex_queue); 

     /* Wait for an item to be sent on the queue */ 
     pthread_cond_wait(&cond_queue, &mutex_queue); <---- waiting here 

     queue_remove(); 
     pthread_mutex_unlock(&mutex_queue); 
    } 

    pthread_exit(NULL); 
} 
+1

recv 스레드에 참여하지 않으면 기본 스레드의 종료가 차단되지 않으며 OS가 둘 다 중지합니다.recv thread가 프로세스 간 자원 등을 보관 유지하지 않는 경우는, OS로 하여금 그것을 정지 시키도록한다. –

답변

9

너 B 기본적으로 다음과 같은 세 가지 선택 사항이 있습니다.

  1. pthread_cancel을 사용하십시오. 그러면 pthread_cond_wait 호출이 중단되고 스레드를 종료하고 pthread_cleanup_push에 등록 된 취소 처리기를 호출합니다.

  2. pthread_kill에서 까지 신호를으로 보냅니다. 이것은 스레드를 "죽이지"않고 신호를 보냅니다. 이 경우 사용하는 신호에 해당 스레드에 신호 처리기를 등록해야하며 해당 신호 처리기는 스레드에 종료를 알리기 위해 무언가를 수행해야합니다. 신호 처리기가 여전히 루프를 종료하기 위해 무언가를해야하기 때문에 이것은 세 번째 옵션보다 특히 좋지 않습니다.

  3. 플래그를 설정하고 조건 변수를 알리는 수동 중단 기능을 스레드에 추가하십시오. pthread_cond_wait 주위의 루프는 플래그를 확인하고 플래그가 설정된 경우 스레드를 종료합니다.

(1) 또는 (3)을 권합니다. pthread_cancel을 사용하는 것이 가장 일반적인 방법이지만 스레드에서주의 깊게 처리해야 스레드에 할당 된 모든 리소스를 정리하고 모든 뮤텍스를 잠금 해제하는 등의 적절한 호출이 필요합니다. 수동 중단 기능을 작성하는 것은 잠재적으로 더 많은 작업이지만 응용 프로그램에 가장 쉽게 맞출 수 있습니다.

+4

4. 필요없는 경우 조인 사용을 중지하십시오. –