Re: Multithreading stuff
- From: Chris Vine <chris cvine freeserve co uk>
- To: michi7x7 <mailing-lists michi7x7 de>
- Cc: gtkmm-list gnome org
- Subject: Re: Multithreading stuff
- Date: Sat, 26 Jun 2010 22:24:24 +0100
On Sat, 26 Jun 2010 12:26:12 +0200
michi7x7 <mailing-lists michi7x7 de> wrote:
>
> The usual way is to send a signal to the thread which tells him to
> stop and wait for him to finish.
> Some libraries provide methods to throw exceptions within the thread,
> which stops him of course.
> I think you can rebuild this behavour by sharing one Dispatcher which
> gets bound by the thread to
> one function throwing an exception.
>
>
> Glib::Dispatcher signal_kill;
>
> class AbortException : public std::runtime_exception {};
>
> void kill_me()
> {
> throw(new AbortException() );
> }
>
> void thread_func()
> {
> signal_kill.connect(sigc::ptr_fun(&kill_me));
>
> doSomethingTricky();
> }
>
> int main()
> {
> Glib::RefPtr<Glib::Thread> thr =
> Glib::Thread::create(sigc::ptr_fun(&thread_func), true);
>
> Glib::usleep(2000);
>
> if(thr->joinable())
> {
> signal_kill();
> thr->join();
> }
> return 0;
> }
>
This won't work. The default constructor of a dispatcher will cause its
callbacks to execute in the main program thread (it can be constructed
to execute in another thread if that other thread has its own main loop,
but your worker thread doesn't have one). Apart from that, connecting
to a dispatcher object is only thread safe if the connection is made in
the same thread as that in which the callback will execute, which you
don't do, and it must also be constructed in that thread.
I am also not sure that a dispatcher can be created as a global object
because at the time of creating it, g_thread_init() will not have been
called (I am not sure about that one).
The trite answer to the OP's problem is that if the OP doesn't know how
to do something as simple as this, he probably shouldn't be programming
with threads because he stands to get quite a few other things wrong.
The more helpful answer is that given the awful design (looping with
usleep() in the worker thread), he can have a flag which is set by the
main program thread and which is read on each iteration by the worker
thread which tells the worker thread to exit by throwing
Glib::Thread::Exit.
To be standard conforming, the flag ought to be protected by a mutex
or be a glib atomic type (I don't think atomic operations are wrapped
in glibmm but if not the glib C interface can be used).
Chris
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]