[英]How to decrement count of barrier on thread completion using pthreads in C
我有一個函數:createrWorkerPool,它將生成“ n”個工作線程,並且每個工作線程都將以pthread_create的args中指定的文件作為輸入,讀取該文件,並通過在其周圍使用互斥鎖修改共享變量,並在所有障礙處等待直到所有線程已完成修改其共享變量。 此操作多次循環發生。
我面臨的問題是讓我們考慮有兩個文件file1和file2,而file2的大小比file1大得多。 屏障同步將一直工作到file1-完成,但是由於完成執行后,它不再到達屏障,並且file2永遠卡在屏障中。
我的問題是,有沒有一種方法可以動態更改在線程退出時屏障正在等待的線程數。 因此,在上述情況下,如果file1提早完成,則會將屏障計數從2減至1,以便file1可以繼續執行。 我嘗試查看手冊頁,但沒有看到任何功能。示例代碼
pthread_mutex_t m1;
pthread_barrier_t b1;
//common function executed by each worker thread
void* doWork(void* arg) {
const char* file = arg;
while(1) {
pthread_mutex_lock(&m1);
// Modify shared variable
pthread_mutex_unlock(&m1);
// Wait for all threads to finish modifying shared variable
pthread_barrier_wait(&b1);
// Once all threads reach barrier check state of shared variable and do some task based on state
// check for condition if true break out of loop
}
return 0;
}
因此,基本上,線程1處理文件1之前完成,線程2永遠卡在障礙處
像這樣使用障礙時,您無法真正更改障礙數。
大概的問題是,經測試可以突破循環的條件並非同時適用於所有文件-即,每個線程可能執行不同數量的循環。
如果是這種情況,一種解決方案是讓每個提前完成的線程繼續循環,但是除了在每個循環中等待障礙之外,什么也不做。 然后安排所有線程一起退出-像這樣:
void* doWork(void* arg)
{
const char* file = arg;
int work_done = 0;
while(1) {
if (work_done)
{
if (all_threads_done)
break;
pthread_barrier_wait(&b1);
continue;
}
pthread_mutex_lock(&m1);
// Modify shared variable
pthread_mutex_unlock(&m1);
// Wait for all threads to finish modifying shared variable
pthread_barrier_wait(&b1);
// Once all threads reach barrier check state of shared variable and do some task based on state
if (finish_condition)
work_done = 1;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.