[완료] C++에서 msgrcv( ) 함수가 메시지 올때까지 기다리도록 하고 싶습니다.
글쓴이: hyde1004 / 작성시간: 목, 2009/12/10 - 8:30오후
안녕하세요.
메시지를 기다리는 프로그램을 작성하고 있습니다.
c로 짜면 다음과 같습니다.
실행하면, 메시지가 올때까지 기다립니다.
#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> struct msgbuf msg_data; int main(void) { int msgid = msgget(IPC_PRIVATE, IPC_CREAT|IPC_EXCL|0666); msgrcv(msgid, &msg_data, 1, 0, 0); msgctl(msgid, IPC_RMID, 0); return 0; }
그런데, C++의 쓰레드에서 해보고 있는데,
다음의 코드를 실행시키면, 메시지를 기다리지도 않고
그냥 지나가버립니다.
msgrcv( )에 IPC_NOWAIT 플래그를 주지도 않았는데 말이죠.
쓰레드와 관련이 있는가 하는 생각만 들뿐입니다.
조언부탁드립니다.
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> class Mythread { public : Mythread(void); ~Mythread(void); void init(void); void destroy(void); static void* thread_func(void* arg); void* run(void* arg); private : pthread_t thread_id; int msg_id; struct msgbuf msg_data; }; Mythread::Mythread(void) { } Mythread::~Mythread(void) { } void Mythread::init(void) { int res = 0; msg_id = msgget(IPC_PRIVATE, IPC_CREAT|IPC_EXCL|0666); if (msg_id == -1) { perror("msg queue creation failed"); exit(EXIT_FAILURE); } res = pthread_create(&thread_id, NULL, thread_func, (void*) this); if (res != 0) { perror("thread creation failed"); exit(EXIT_FAILURE); } } void Mythread::destroy(void) { int res = 0; void* thread_result; res = msgctl(msg_id, IPC_RMID,0); if (res == -1) { perror("msg destroy failed"); exit(EXIT_FAILURE); } res = pthread_join(thread_id, &thread_result); if (res != 0) { perror("thread destroy failed"); exit(EXIT_FAILURE); } } void* Mythread::thread_func(void* arg) { Mythread *pthread = (Mythread* ) arg; return pthread->run(NULL); } void* Mythread::run(void* arg) { for(int i=0;i<2;i++) { std::cout << "running in thread..." << std::endl; sleep(1); } for(int i=0;i<3;i++) { size_t data_length = 0; data_length = msgrcv(msg_id, &msg_data, 1, 0, 0); printf("msg id : %d, data_length : %d\n", msg_id, data_length); std::cout << "received data " << std::endl; } pthread_exit(NULL); } int main(void) { Mythread athread; athread.init(); athread.destroy(); std::cout << "Program complete" << std::endl; return 0; }
Forums:
Mythread::run 의 msgrcv
Mythread::run 의 msgrcv 호출중에 혹은 그보다 먼저 Mythread::destroy의 msgctl 가 호출되서 그런거 같은데요
메시지를 확실히 다 받으시려면 msgctl 보다 pthread_join 를 먼저 호출하셔야 할거 같네요
그렇군요..
그렇군요..
감사합니다..
Thread 죽이는 동안 혹시 Message를 받게 될까 싶어,
메시지 박스를 먼저 지웠더니 그런 일이 생기게 된거네요..
댓글 달기