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