2013-01-11 88 views
1

我使用Glib來開發多線程C軟件。Glib:如何啓動一個新的線程,直到另一個線程完成?

我想有一組活動線程。一旦某個線程完成,另一個線程以不同的參數開始。它就像一個線程池。

我使用glib thread來實現多線程。但是我找不到很多來自Google的教程。我現在可以開始一組線程,但不知道等待。我的一些代碼:

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); 
} 

回答

2

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; 
    } 
} 
相關問題