On 19 Feb 2010, at 13:25, Tom Smith wrote:
> Hello,
>
> I'm doing a small project that needs to use threads.h and I have it
> mostly working. Having never written threaded programs, I have a
> question about Fl_Button and fl_create_thread.
>
> I'd like a thread to be created when the user clicks a button. So,
> would I put fl_create_thread in the callback function like so:
I think what you are missing is that you have not attached a callback
to your button, so the button does not know what to do when you click
on it.
Here's a simple example that shows what you might do:
-------------------
/* Thread Test Code */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Button.H>
#include "threads.h"
#ifdef WIN32
# define wait_here(x) Sleep(x) // delay in milliseconds
# define SCHED_YIELD Sleep(0)
#else
# include <sched.h> // maybe necessary for sched_yield ?
# define wait_here(x) usleep((x)*1000) // delay in milliseconds
# define SCHED_YIELD sched_yield()
#endif
#define MAX_THRDS 20
static int keep_running = -1;
static int active_thrds = 0;
static Fl_Double_Window *main_win=(Fl_Double_Window *)0;
static Fl_Button *exit_bt=(Fl_Button *)0;
static Fl_Button *add_bt=(Fl_Button *)0;
void* thread_task(void* p) {
long id = (long)p;
printf("Start thread %ld\n", id); fflush(stdout);
while(keep_running) {
wait_here(1000); // delay for a second
printf("Hello from thread %ld\n", id); fflush(stdout);
}
return 0;
}
static void cb_exit_bt(Fl_Button*, void*) {
keep_running = 0;
main_win->hide();
}
static void cb_add_bt(Fl_Button*, void*) {
// add new thread button
if (active_thrds < MAX_THRDS) {
Fl_Thread thread_id;
active_thrds++;
fl_create_thread(thread_id, thread_task, (void *)active_thrds);
}
}
int main(int argc, char **argv) {
Fl::scheme("gtk+");
main_win = new Fl_Double_Window(316, 231, "Threads Tester");
exit_bt = new Fl_Button(230, 190, 64, 20, "Quit");
exit_bt->callback((Fl_Callback*)cb_exit_bt);
add_bt = new Fl_Button(15, 65, 64, 20, "Add");
add_bt->callback((Fl_Callback*)cb_add_bt); // add a callback to the
add-thread button
main_win->end();
main_win->show(argc, argv);
keep_running = -1; // set this zero to kill all the child threads
return Fl::run();
}
/* End of File */
-------------------
_______________________________________________
fltk mailing list
[email protected]
http://lists.easysw.com/mailman/listinfo/fltk