Re: About gthread cancellation

Hi Davi,

> 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):
> 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?

I suggest using poll/select in the other threads (I wouldn't use the
GLib main loop though, you would need a dedicated GMainContext for every
thread and they are comparatively expensive) and additionally one pipe,
which is polled by all threads. Upon exit write 1 char into the pipe and
simply exit a thread that finds data at that pipe in a select/poll.

Regarding your concerns of using select/poll in a multi-threaded
application I can assure you, that it should work on all major

Sebastian Wilhelmi                 |            här ovanför alla molnen
mailto:seppi seppi de              |     är himmlen så förunderligt blå                    |

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