Re: About gthread cancellation

On Sat, 2004-05-01 at 19:48, Davi de Castro Reis wrote:
> Hi all,
> I searched through the archives and found that glib does not have an 
> equivalent of pthread_cancel because the developers decided not to have 
> it. I agree that pthread_cancel can be tricky, but I have gone through a 
> lot of work to build a server application using glib code, and now I am 
> stuck because of the lack of a cancellation function. My code is very 
> simple (standard server pseudo-code):

Unless you actually need portability between Unix and windows, I'd
suggest that you use pthreads directly; if you are counting on pthreads
being there, there is no real benefit to using the GLib thread function
for things like thread creation; you can still use all the GLib thread
safety and even threading constructs like GAsyncQueue fine.

> while(1) {
> 	accept(); // man 2 accept
> 	g_thread_create(listen_and_reply);
> }
> The point now is that I want to exit the loop upon some condition (e.g. 
> SIGTERM caught) so my application can exit gracefully (cleaning memory 
> and, the more important, closing databases to avoid corruption).
> If I had a g_thread_cancel call, I could do something like this:
> while(1) {
> 	accept_thread = g_thread_create(accept);
>          cancel_accept = g_thread_create(cancel_accept_upon_condition);
> 	g_thread_join(accept);
> 	g_thread_cancel(cancel_accept);
> }
> The function cancel_accept_upon_condition would call g_thread_cancel to 
> cancel accept_thread upon the observation of some condition (GCond). 
> And, just to avoid a race condition, the accept_thread should call 
> set_cancelstate(CANCEL_DISABLE) just before exiting.
> My doubt is: if I don't have g_thread_cancel, how can I implement this 
> simple server loop? The only other solution I can see is to use 
> no-blocking mode and select() with timeouts, which is rather ugly and 
> not desired if I do use threads. Any tips?

[off-topic advice]

IMO, you are creating far worse problems for yourself by bringing
cancellation into the picture than the small amount of trouble necessary
to do non-blocking accepts. 

It's probably also possible to wake the thread out of the accept() by
sending it a signal (so the accept will return EINTR) but there's
considerable portability traps there.

You could also take the very simple approach of simply letting your
accept() thread run until your app exits and simply close the new
connection immediately if you happen to get a new connection between
the point where you start cleaning up and the point where the app


Attachment: signature.asc
Description: This is a digitally signed message part

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]