Re: Still confused on new thread starting idle functions to update UI.



On Thu, Dec 5, 2013 at 2:56 AM, David Buchan <pdbuchan yahoo com> wrote:
Making the pointer to textview global would indeed simplify things
enormously. I guess I avoid global variables like the plague, having been
told to for years. Also wanted to make the idle function generic.

Yeah, lots of people have been taught to hate globals. The fact is
that they have their uses. Sometimes your code simply doesn't need
more flexibility than that - do you really expect your process to be
running two copies of its main window? If not, there's no reason not
to have your main window referenced globally!

However, this applies to *applications*. Libraries should be a lot
more careful about their use of globals - it's much more likely that
two parts of the application will want the same function (look at
strtok() for an example). With your main application, you can recode
it to not use globals when the situation changes, with a library you
aren't in control of that.

As promised, here's a simple Pike program that listens for socket connections.

//Some things can be stored globally
GTK2.TextView textview;
Stdio.Port mainsock;

//Called when the user closes the window
void window_close()
{
    exit(0);
}

//Called when a socket has written something
void read_callback(Stdio.File sock, string data)
{
    GTK2.TextBuffer buf = textview->get_buffer();
    buf->insert(buf->get_end_iter(), data, -1);
}

//Called when a socket client connects
void accept_callback()
{
    Stdio.File sock = mainsock->accept();
    sock->set_nonblocking(read_callback);
}

int main()
{
    GTK2.setup_gtk();
    GTK2.Widget mainwindow = GTK2.Window(GTK2.WindowToplevel)
        ->add(textview = GTK2.TextView())
        ->show_all();
    mainwindow->signal_connect("delete-event", window_close);
    mainsock = Stdio.Port(1234, accept_callback);
    return -1; //Hand control to the asynchronous back-end handler
}



See how many lines of code are dedicated to allocating and
deallocating memory? None whatsoever! See how much effort goes into
making sure everything's thread-safe? The same amount, because this
isn't even threaded - though it will happily handle any number of
simultaneous clients.

To try this out, run it (which will need a Pike interpreter - you
might be able to "apt-get install pike" or "yum install pike",
otherwise go to http://pike.lysator.liu.se/ to grab one), and then in
a separate window, telnet to localhost port 1234 (on most platforms,
"telnet localhost 1234" will do that). Everything you type in telnet
will come up in the textview.

Porting this code to Python is left as an exercise to the reader, if
anyone feels like using a less-obscure language :) But I like Pike;
also, its C-like syntax should help you feel at home here.

ChrisA


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