我目前正在創建一種演算法,用于使用具有多執行緒的動態編程來解決 0-1 背包問題。我的方法是n通過capacity將動態規劃表分成 4 個n部分capacity / 4來解決,這將由 4 個執行緒解決。由于背包依賴于上排,所以4個執行緒每次都需要求解同一行。他們必須等待所有執行緒完成其在當前行上的部分,然后才能繼續下一行。
這是我的代碼:
int knapsackParallel(char *values, char *weights, int N, int capacity) {
for (int j = 0; j < 4; j ) {
arguments[j].cpuNum = j;
pthread_create(&tid[j], NULL, solveRow, (void *) &arguments[j]);
pthread_setaffinity_np(tid[j], sizeof(cpu_set_t), &cpusets[j]);
}
for (int j = 0; j < 4; j ) {
pthread_join(tid[j], NULL);
}
}
以下是需要同步的每個執行緒的代碼:
void *solveRow(void *arguments) {
int cpuNum = ((args *) arguments)->cpuNum;
int initial = ((args *) arguments)->cpuNum * (capacity / p);
int limit = cpuNum == p - 1 ? capacity 1 : initial (capacity / p);
for (int i = 0; i < N 1; i ) {
for (int j = initial; j < limit; j ) {
// for the top and left edges, initialize to 0
if (i == 0 || j == 0)
table[i][j] = 0;
// find the max between putting the value in the knapsack or not
else if (weights[i] <= j)
table[i][j] = fmax(values[i] table[i - 1][j - weights[i]], table[i - 1][j]);
// copy the value in the top of the cell
else
table[i][j] = table[i - 1][j];
}
// insert code here to wait for all the threads to finish their current iteration
// before proceeding to the next iteration
}
到目前為止我已經嘗試過:
使用多個信號量:
sem_post(&locks[cpuNum]);
sem_post(&locks[cpuNum]);
sem_post(&locks[cpuNum]);
for (int j = 0; j < p; j ) {
if (j == cpuNum) continue;
sem_wait(&locks[j]);
}
printf("thread %d done\n", cpuNum);
使用pthread_cond_wait:
locks[cpuNum] = 1;
if (locks[0] && locks[1] && locks[2] && locks[3]) {
pthread_cond_broadcast(&full);
}
else {
pthread_cond_wait(&full, &lock);
}
locks[cpuNum] = 0;
使用futex:
locks[cpuNum] = 1;
futex_wait(&locks[0], 0);
futex_wait(&locks[1], 0);
futex_wait(&locks[2], 0);
futex_wait(&locks[3], 0);
locks[cpuNum] = 0;
uj5u.com熱心網友回復:
這聽起來像是 posix 障礙的作業:
問題似乎是您沒有在要同步的執行緒中呼叫
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482581.html
上一篇:硒中的ElementNotInteractableException(Python)
下一篇:c#讓我的特定行在x秒后超時c#
