Re: Question about Threads y gtk+



On Fri, 3 Oct 2008 09:37:23 -0700 (PDT)
Moises <ammoises yahoo com mx> wrote:
> The problem is that I'm doing a program in which the user calls a
> function, which I put on a thread to work, but I do not have any
> mechanism in communication between the main thread and son thread. 
> 
> But at some point the user can no longer required that this function
> working, then I need to pull the thread, but I do not have any kind
> of communication between the two threads, as you can send the signal
> to expire.
> 
> in POSIX there is function.
> int pthread_kill(pthread_t thread, int sig);
> but with gtk+ how can I do this? 

pthread_kill() does not do what you think it does - it does the
equivalent of kill(). You are probably thinking about pthread_cancel().

There is no equivalent of pthread_cancel() with GThreads, mainly
I suspect because windows does not adequately support thread
cancellation, but if you are using glib under a unix like operating
system rather than under windows threads, you can call pthread_cancel()
directly if you want.

You should generally avoid pthread_cancel() in a C++ program because it
does not necessarily call the destructors on local objects in scope
(that depends on the implementation - linuxthreads does not, but NPTL
does by means of a pseudo-exception, and HPUX and I believe recent
Solaris do too).

You should be careful even in C programs and always use deferred
cancellation.  Also, look at the POSIX documentation on cancellation
points (nearly all blocking POSIX functions are cancellation points),
and use pthread_cleanup_push() and pthread_cleanup_pop() for cleanup of
resources.

However, try to avoid thread cancellation if you can.  Try to avoid
calls to blocking system functions in threads you might want to have
terminate, and communicate with the thread eg with GAsyncQueue and get
the thread to terminate itself.  You can also give your worker thread
its own GMainContext/GMainLoop objects and communicate with that thread
by means of pipes/GIOChannel/gio - this will work under windows and is
generally the best way of doing it.

You can actually sometimes also use pthread_kill() to do what you
want, depending on what you are doing, provided that the SA_RESTART
flag is not set.  When a blocking function returns with errno set to
EINTR the receiving thread can examine a flag (mutex protected to ensure
memory visibility) to see whether it should commit suicide. This would
not of course work under windows.

Chris


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