【问题标题】:Glib: how to start a new thread until another thread is finished?Glib:如何在另一个线程完成之前启动一个新线程?
【发布时间】:2013-01-11 06:58:58
【问题描述】:

我正在使用Glib 开发一个多线程C 软件。

我想要一组活动线程。一旦某个线程完成,另一个线程就会以不同的参数开始。它类似于线程池。

我正在使用glib thread 来实现多线程。但是我在谷歌上找不到很多教程。我现在可以启动一组线程,但不知道等待。我的一些代码:

GThread *threads[n_threads];
thread_aux_t *data = (thread_aux_t*) calloc(n_threads, sizeof(thread_aux_t));
for (i = 0; i < n_threads; ++i) {
    data[i].parameter = i;
    threads[i] = g_thread_create((GThreadFunc) pe_lib_thread, data + i,
            TRUE, NULL);
}

/* wait for threads to finish */
for (i = 0; i < n_threads; ++i) {
    g_thread_join(threads[i]); // How to start a new thread depending on the return value?
}
free(data);

谢谢。


问题解决了。更新:

刚刚找到了一个glib的线程池实现:Thread Pools。我已经运行它并且它工作正常。 代码写成:

// 'query' is for this new thread, 
// 'data' is the global parameters set when initiating the pool
void *pe_lib_thread(gpointer query, gpointer data) {
}

void run_threads() {
    GThreadPool *thread_pool = NULL;
    // Global parameters by all threads.
    thread_aux_t *data = (thread_aux_t*) calloc(1, sizeof(thread_aux_t));

    data->shared_hash_table = get_hash_table();
    g_thread_init(NULL);
    thread_pool = g_thread_pool_new((GFunc) pe_lib_thread, data, n_threads,
            TRUE, NULL);
    // If n_threads is 10, there are maximum 10 threads running, others are waiting.
    for (i = 0; i < n_queries; i++) {
        query = &queries[i];
        g_thread_pool_push(thread_pool, (gpointer) query, NULL);
    }
    g_thread_pool_free(thread_pool, 0, 1);
}

【问题讨论】:

    标签: c multithreading glib


    【解决方案1】:

    g_thread_join 返回返回值,所以你只需检查它。 假设您要创建一个新进程,如果返回值为 17。

    for (i = 0; i < n_threads; ++i) {
        if (threads[i] && g_thread_join(threads[i]) == 17) {  
            /* Start a new thread. */
            threads[i] = g_thread_create((GThreadFunc) pe_lib_thread, data + i,
                TRUE, NULL);
        } else {
            threads[i] = NULL;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多