我正在處理 CS 分配,我必須使用 p_threads 來計算陣列的前綴總和。教授告訴我們使用 Hillis 和 Steele 演算法。
我有點堅持在實際代碼中實作這一點。我們的程式應該作業的方式是,用戶通過檔案或標準輸入傳入一個陣列,然后接下來的 2 個引數是輸入陣列的大小,以及我們需要使用多少執行緒。所以,我假設這張圖片中的“n”是“我們需要使用的執行緒數量”。然后,我不確定 x 上的符號是什么意思。維基百科說“在上面,符號......表示時間步長 i 中陣列 x 的第 j 個元素的值。” 但是……什么?我如何實作這個“時間步”?我假設它的意思是:“做 j 的 i 1 次方,然后在陣列 x 中找到那個索引元素”。有了這個假設,我寫了這段代碼:
void scan(int numThreads, int* vector, pthread_t* threads){
for(int i = 0; i < logbase(numThreads, 2); i ){
for(int j = 0; j < numThreads - 1; j ){
// create a thread here to perform parallel()
int* args = calloc(3,sizeof(int));
args[0] = i;
args[1] = j;
args[2] = *vector;
pthread_create(&threads[j], NULL, parallel, (void*)args);
free(args);
}
}
}
// each thread runs this function
void* parallel(void *arg){
int i = ((int*)arg)[0];
int j = ((int*)arg)[1];
int* vector = ((int**)arg)[2];
if(j < pow(2, i)){
// store current element (jth element of array x to the power of i)
// in the jth element of array x to the power of i 1
vector[(int)pow(j, i 1)] = vector[(int)pow(j, i)]; // ISSUE IS HERE
}
else{
// store current element plus element at j-2^i ^i in current^i 1
vector[(int)pow(j, i 1)] = vector[(int)pow(j, i)] vector[(int)pow(j -
pow(2, i), i)];
}
return NULL;
}
該行注釋了“ISSUE IS HERE”段錯誤。我可以逐步進入 gdb 并弄清楚為什么它會出現段錯誤,但我想知道我是否做得對。這是我第一次用多執行緒做任何事情。我們還應該使用鎖和條件變數的組合來創建自己的障礙,但我什至不知道該怎么做。
此外,有些代碼沒有顯示出來,例如我的“logbase”函式和讀取輸入陣列的函式。我知道那些作業正常。
感謝您的時間。
uj5u.com熱心網友回復:
你的問題就在這里,你試圖傳遞一個指向向量的指標
args[2] = *vector;
但是,您只需傳入第一個元素,然后將其視為病房后的指標,那將不起作用。您需要傳入指標,但這可能不適合您保留的空間。
如果您必須像這樣傳遞引數(而不是簡單地創建一些靜態全域變數),那么您應該這樣做
struct args_t
{
int i;
int j;
int * vector;
};
然后
struct args_t *args = malloc(sizeof(struct args_t));
args->i = i;
args->j = j;
args->vector = *vector;
pthread_create(&threads[j], NULL, parallel, (void*)args);
然后在接收端添加相應的代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/433070.html
上一篇:將更改提交到不同的分支
下一篇:解釋協程的有趣行為
