2 * Copyright 2005-2016, Haiku.
3 * Distributed under the terms of the MIT License.
6 * Axel Dörfler, axeld@pinc-software.de
10 #include "MessageLooper.h"
18 MessageLooper::MessageLooper(const char* name
)
28 MessageLooper::~MessageLooper()
36 BAutolock
locker(this);
40 char name
[B_OS_NAME_LENGTH
];
41 _GetLooperName(name
, sizeof(name
));
43 // Spawn our message-monitoring thread
44 fThread
= spawn_thread(_message_thread
, name
, B_DISPLAY_PRIORITY
, this);
50 if (resume_thread(fThread
) != B_OK
) {
54 return B_BAD_THREAD_ID
;
68 // thread has not been started yet
73 if (fThread
== find_thread(NULL
)) {
74 // called from our message looper
78 // called from a different thread
79 PostMessage(kMsgQuitLooper
);
85 \brief Send a message to the looper without any attachments
86 \param code ID code of the message to post
89 MessageLooper::PostMessage(int32 code
, bigtime_t timeout
)
91 BPrivate::LinkSender
link(MessagePort());
92 link
.StartMessage(code
);
93 return link
.Flush(timeout
);
99 MessageLooper::WaitForQuit(sem_id semaphore
, bigtime_t timeout
)
103 status
= acquire_sem_etc(semaphore
, 1, B_RELATIVE_TIMEOUT
, timeout
);
104 } while (status
== B_INTERRUPTED
);
106 if (status
== B_TIMED_OUT
)
114 MessageLooper::_PrepareQuit()
116 // to be implemented by subclasses
121 MessageLooper::_GetLooperName(char* name
, size_t length
)
123 sem_id semaphore
= Sem();
125 if (get_sem_info(semaphore
, &info
) == B_OK
)
126 strlcpy(name
, info
.name
, length
);
128 strlcpy(name
, "unnamed looper", length
);
133 MessageLooper::_DispatchMessage(int32 code
, BPrivate::LinkReceiver
&link
)
139 MessageLooper::_MessageLooper()
141 BPrivate::LinkReceiver
& receiver
= fLink
.Receiver();
145 status_t status
= receiver
.GetNextMessage(code
);
147 // that shouldn't happen, it's our port
149 _GetLooperName(name
, 256);
150 printf("MessageLooper \"%s\": Someone deleted our message port %"
151 B_PRId32
", %s!\n", name
, receiver
.Port(), strerror(status
));
157 if (code
== kMsgQuitLooper
)
160 _DispatchMessage(code
, receiver
);
168 \brief Message-dispatching loop starter
172 MessageLooper::_message_thread(void* _looper
)
174 MessageLooper
* looper
= (MessageLooper
*)_looper
;
176 looper
->_MessageLooper();