gpt4 book ai didi

c - 运行多个并发 GMainLoops

转载 作者:太空狗 更新时间:2023-10-29 16:38:34 24 4
gpt4 key购买 nike

是否允许 GLib 用户在多个线程中同时运行多个 GMainLoop 实例,每个线程运行自己的实例?我到处都找到了"is"和“否”的答案。我意识到这个问题之前已经在这个论坛上被问过 (December 2011) .

但是,我可以同时运行两个 GMainLoop 实例而不会出现明显问题。我的测试代码很简单:

  1. main() 中创建一个 GMainLoop
  2. 使用 g_timeout_add 为默认上下文和主循环创建超时源
  3. 在 main() 中创建一个 GThread
  4. 使用g_main_loop_run 运行主循环
  5. [线程上下文]:使用 g_main_context_new 创建上下文
  6. [THREAD CONTEXT]:使用 g_main_context_push_thread_default 将该上下文设置为线程默认值
  7. [THREAD CONTEXT]:使用 g_main_loop_new 创建一个循环并为其提供新的上下文
  8. [THREAD CONTEXT]:创建超时源,并通过g_source_attach 将其附加到新上下文。
  9. [THREAD_CONTEXT]:让线程调用g_main_loop_run

这样做,我看到 GMainLoop 的两个实例都工作正常。超时回调被正确调用,随后对 g_main_loop_quit 的调用按预期工作。

因此,多个 GMainLoop 实例并发工作看起来不是问题。但也许我只是没有足够地使用 API 来完全掌握情况。这个问题有确定的答案吗?

此外,如果有人想看的话,这里是实际的测试代码:

#define THREAD_TIMEOUTS (20)
#define MAIN_TIMEOUS (1)

typedef struct timeout_struct
{
int i;
int max;
GMainLoop *loop;
char *name;

} TIMEOUT_STRUCT;

gboolean timeout_callback(gpointer data)
{
TIMEOUT_STRUCT *psTimeout = (TIMEOUT_STRUCT *)data;

psTimeout->i++;

if (psTimeout->i == psTimeout->max)
{
if (psTimeout->max == THREAD_TIMEOUTS)
{
g_main_loop_quit( (GMainLoop*)psTimeout->loop );
}
return FALSE;
}

return TRUE;
}
void* thread_function(void *data)
{
GMainContext *ps_context;
GMainLoop *ps_loop;
GSource *ps_timer;
TIMEOUT_STRUCT sTimeout;

ps_context = g_main_context_new();
g_main_context_push_thread_default(ps_context);

ps_loop = g_main_loop_new(ps_context, FALSE);

sTimeout.i = 0;
sTimeout.max = THREAD_TIMEOUTS;
sTimeout.loop = ps_loop;
sTimeout.name = "thread";
ps_timer = g_timeout_source_new_seconds(1);
g_source_set_callback(ps_timer, timeout_callback, &sTimeout, NULL);
g_source_attach(ps_timer, ps_context);

g_main_loop_run(ps_loop);

g_main_loop_quit( (GMainLoop*)data );

return NULL;

}
/*
* This main boots a thread, then starts up a GMainLoop. Then the thread runs
* a GMainLoop. The thread sets a timer that fires ten times and the main sets a
* timer that fires two times. The thread quits and
* and then the other main l
*
*
* */
int main()
{
GThread *ps_thread;
GMainLoop *loop;
TIMEOUT_STRUCT sTimeout;

loop = g_main_loop_new ( NULL , FALSE );

sTimeout.i = 0;
sTimeout.max = MAIN_TIMEOUS;
sTimeout.loop = loop;
sTimeout.name = "main";

// add source to default context
g_timeout_add (1 , timeout_callback, &sTimeout);

ps_thread = g_thread_new("thread", thread_function, loop);

g_main_loop_run (loop);
g_main_loop_unref(loop);
}

最佳答案

《Foundations of GTK+ Development》一书这样说:

The GLib main loop is implemented as a number of structures, which allow multiple instances to be run concurrently.

因此,鉴于此,我的测试代码和 link我在上面的评论中发表了我们对这个问题的明确答案。

即:多个线程可能有自己的 GMainContext 和 GMainLoop,并且能够以并发方式独立运行这些循环。

关于c - 运行多个并发 GMainLoops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21485642/

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