gpt4 book ai didi

c - GTK+3 GUI 随机卡住(1 小时后或 20 分钟后)

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:42 24 4
gpt4 key购买 nike

我正在用 C 开发一个程序,它使用 GTK+3 并或多或少地遵循 MVC 架构:

  • 模型通过调用 model_update 每 20 毫秒更新一次(它不调用 GTK 函数);
  • 通过读取模型变量每 50 毫秒调用 gui_update 来更新 GUI。

我的问题是 GUI 在随机运行一段时间后卡住,可能是 20 分钟或 1 个多小时,我不知道为什么。也许我应该了解一些关于 GTK 的信息?

注意:使用互斥锁保护对模型变量的访问。

非常感谢您的帮助!!

#include <signal.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/prctl.h>

void *
thread_gui(void* data)
{
g_timeout_add(50, handler_timer_gui_update, NULL); // updates the GUI each 50ms
gtk_main();
pthread_exit(NULL);
}

gint
handler_timer_gui_update(gpointer data)
{
gui_update();
// gui_update reads the model and updates GUI by using
// gtk_label_set_text, gtk_spin_button_set_value, cairo_paint
return TRUE;
}

void
launch_periodical_call_updating_model( )
{
signal( SIGRTMIN + 1, model_update );

timer_t timer;
struct sigevent event;
event.sigev_notify = SIGEV_SIGNAL;
event.sigev_signo = SIGRTMIN + 1;
event.sigev_value.sival_ptr = &timer;
timer_create(CLOCK_REALTIME, &event, &timer);

struct itimerspec spec;
spec.it_value.tv_nsec = 20 * 1000000; // updates the model each 20 ms
spec.it_value.tv_sec = 0;
spec.it_interval = spec.it_value;

timer_settime( timerModel, 0, &spec, NULL);
}

int
main( int argc, char *argv[] )
{
pthread_t pthread_gui;

init_model( ); // init model variables
launch_periodical_call_updating_model( );

// signal capture to exit
signal( SIGINT, ctrlc_handler );
signal( SIGTERM, ctrlc_handler );

// GUI
g_thread_init(NULL);
gdk_threads_init();
gdk_threads_enter();
gtk_init( &argc, &argv );
create_gui ( ); // building GTK Window with widgets
pthread_create(&pthread_gui, NULL, thread_gui, NULL);
gdk_threads_leave();

// Leaving the program
pthread_join( pthread_gui, NULL );
stop_model( ); //It stops to update the model and releases memory

return 0;
}

void
ctrlc_handler( int sig )
{
gtk_main_quit();
}

最佳答案

您不应该将 Unix 信号与 GTK 一起使用。参见 signal-safety(7)signal(7) .

您应该考虑仅使用 Glib 计时器(而不是使用任何 POSIX 计时器)。了解 Glib event loop (在 GTK 中使用)并使用 g_timeout_add或相关功能。

如果您坚持在 GTK 程序中处理 Unix 信号,请执行以下操作 Qt recommends关于他们:设置 pipe(7)在初始化时 self ,并轮询您的 Unix 信号处理程序将 g_source_add_unix_fd 的文件描述符(在 GTK 中,使用 g_io_channel_unix_newwrite(2)) (一次一个或很少几个字节)。顺便说一句,Linux 还提供了 signalfd(2) .

最后,GTK 并不是真正的线程友好(另见 this ),所有 GTK 函数都应该(仅)从您的主线程(而不是从其他一些 pthread_gui)调用。实际上,如果您真的需要使用多个线程进行编码,请考虑让您的非 GUI 线程也通过管道与 GTK 进行通信和同步,并使用 Glib thread functions。启动和管理它们。

您甚至可以考虑一些多处理方法:在一个进程中使用 GUI 程序,在另一个进程中进行其他处理(多线程)(可能由使用 g_spawn_async_with_pipes 的 GUI 程序启动)。

了解 continuationscontinuation-passing style .它可能会帮助您从这些方面进行思考。

关于c - GTK+3 GUI 随机卡住(1 小时后或 20 分钟后),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47442563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com