2011-12-04 46 views
0

我對python並不熟悉。我想並行化以下僞代碼的外部for循環:如何在python中使用多線程並行化循環

for(i=1 to N){ // N and n will be taken as input for the shell script. 
    min=some garbage value 
    for(j=1 to n){ 
     val= './a.out' // call the executable a.out and take the output in val 
     if(val<min) // a.out is a random number generator script 
      min=val; 
    } 
    arr[k++]=min; 
} 
// Then I want to calculate the sum of the elements of the array 'arr'. 

我試圖使用shell腳本,如下所示。但是N可能非常大。所以,我需要使用 多線程來並行化外循環。

#!/bin/bash 
# set min to some garbage value 

N=$1 
n=$2 
for ((i=1; i<=$N; i++)); do 
    min=100000000 
    for ((j=1; j<=$n; j++)); do 
     val=$(/path/to/a.out) 
     val2=`echo $val | bc` // is this the correct syntax? 
     if (($val2 < $min)); then 
      min=$val2; 
     fi 
    done 
    arr=("${arr[@]}" "$min") 
done 

# Then I want to calculate the sum of the elements of the array 'arr'. 
sum=0 
for ((l=0; l<${#arr[@]}; l++)); do 
    sum=$(expr $sum + ${arr[$l]}) 
done 

echo "Sum of \$arr = ${sum}" 
+0

是你的號碼發生器程序需要大量的CPU時間?如果不是,那麼在多線程中運行內部循環時幾乎不會獲得任何好處。幾乎不需要一次同步來計算最小值並且一次更新arr。 – Abhijit

+0

你需要使用一個編譯的隨機數發生器嗎? Python有一個「隨機」模塊。 Python還可以通過內置的sum函數將數組中的所有元素相加(例如'sum([1,2,3])'將給出6)的答案。 –

回答

0

我回答,以供將來參考的問題,即使我同意其他海報上並列化是否遵循這個具體的例子正確的道路提出的關注。

要將簡單的for循環與線程並行化,當然可以使用threading module。另外,joblib在它們之上帶來了更簡單的語法(請小心將其切換到線程後端)。

聲明:我是joblib的原作者。