On 08/12/12 17:45, Amadeus W.M. wrote: > I'm trying to create my first threaded application with fltk. I have two > threads: one that produces stuff and the gui thread. For simplicity, the > producer thread just generates random rectangles and tells the gui thread > to draw them via Fl::awake(). See code below. > > The problem is I have to put the producer thread to sleep() for a few > seconds right at the beginning of the thread function, to allow for > everything else to get going. See makeRectangles() below. > > I imagine this is not the proper way to make sure all threads have > started, so what's the right way?
I usually create a mutex, and use it to manage a small bit of data that communicates a readiness state. So for instance if you want to wait for three threads to start, I'd suggest making a 'thread counter' that gets incremented each time a thread starts, and decremented when one exits. Then use a mutex to protect this counter, so that whenever you look at or change the counter, you lock it first. This keeps the locks short, preventing deadlocks. BTW, don't forget to either 'join' or 'detach' the threads to avoid leaking memory, esp. if your app starts and stops threads repeatedly. > Also, the threads.cxx example from fltk-1.1 locks/unlocks in the > "producer" thread, but that's because it adds rows to the browsers. I'm > not accessing any fltk widgets, so I don't have to lock, is that correct? I think that's correct; you'd only need to use FLTK's locks if you need to do anything to the widgets. You'll need to lock something though, if you want the parent and child threads to share data of any kind; always lock any data across the threads, and be particularly mindful of ANY global data between the threads, including OS calls that return static data. > Finally, there seems to be another way of drawing from a non-gui thread > in the gui thread, using Fl::add_fd(), as explained here: > http://www.angelfire.com/linux/tzptech/fltk/fltk-mt.pdf > Is this what Fl::awake() does behind the scenes? Mmm, add_fd() is a way (on unix at least) to read eg. a pipe or network connection without blocking the GUI by having a callback invoked when data is ready on the pipe. On some platforms (Mac) it uses a thread underneath to handle sending signals to the main thread, and on some platforms (X11) it doesn't use a thread. But you shouldn't have worry about that implementation specific detail; to the app it should seem like a single threaded operation in either case. _______________________________________________ fltk mailing list fltk@easysw.com http://lists.easysw.com/mailman/listinfo/fltk