GTK3 and multithreading, replacing deprecated functions

后端 未结 3 1955
深忆病人
深忆病人 2020-12-09 12:30

I would like to replace deprecated functions gdk_threads_enter()/leave() in my application that uses threads. The application as it is now, works perfect (a

3条回答
  •  借酒劲吻你
    2020-12-09 12:54

    What the documentation says is that you can still run your worker function in a thread, you just can't use GTK and GDK functions from that thread. So, you can still start the thread when you click start. But instead of updating GUI elements from the thread, you have to schedule them to be updated from the main thread by using gdk_threads_add_idle().

    So your diagram should look something like this:

    Main thread     Worker thread
        |
    Button clicked
        |      \________
        |               \
        |           Start worker function
        |                |
        |           Computation
        |                |
        |           Want to update GUI
        |                |
        |           gdk_threads_add_idle(function1, data1)
        | ______________/|
        |/               |
        v           More computation
    function1 runs       |
        |           Want to update GUI
    GUI updated          |
        |           gdk_threads_add_idle(function2, data2)
        | ______________/|
        |/               |
        v           More computation
    function2 runs       |
        |      
      etc...
    

    If this is too complicated for your use case, and you have a computation in your worker thread that returns control to your worker thread often enough (say, you are calculating something in a loop), then you can run the calculation entirely in the main thread without locking up the GUI by briefly returning control to the GUI main loop, like so:

    for (lots of items) {
        result = do_short_calculation_on(one_item);
    
        update_gui(result);
    
        while (gtk_events_pending())
            gtk_main_iteration();
    }
    

提交回复
热议问题