linux2021
目的: 檢驗學員對 bitwise operation 及 並行和多執行緒程式設計 的認知
1
3 月 14 日是圓周率日,這天也是愛因斯坦的生日,求圓周率近似值的討論可見:
Gregory-Leibniz 級數可優雅地計算圓周率,參考 Leibniz's Formula for Pi。從下面的 Madhava–Leibniz series 開始推導:
首先積分下列數列
從 積分到 ,
先看 ,因為 ,得到
又因為
依據夾擠定理 (squeeze theorem,也稱為 sandwich theorem),當 ,於是得出下列式子
而且
此時將 代入 1,即可得
以下是對應實作:
比較單執行緒、多執行緒和 SIMD 版本的表現:
1995 年提出的 Bailey–Borwein–Plouffe formula,可用這三位發表者的姓氏開頭簡稱為 BBP 公式,最初的公式如下:
BBP 公式跳脫典型的圓周率的演算法,可計算圓周率的任意第 位,而不用事先計算前面的 位,於是 BBP 公式很適合透過並行運算來求圓周率近似值。
在 並行和多執行緒程式設計 提到 thread pool,如此設計的考量如下:
用醫院來比喻:
示意圖:
以下是一個 thread pool 實作:
我們使用 Bailey–Borwein–Plouffe formula 和上述的 thread pool 撰寫求圓周率近似值的程式碼:
預期執行輸出:
請補完程式碼,使執行結果符合預期。
作答區
FFF = ?
(a)
pthread_cond_wait(&future->cond_finished, &future->mutex)
(b)
pthread_cond_wait(&future->mutex, &future->cond_finished)
(c)
pthread_cond_broadcast(&future->cond_finished, &future->mutex)
(d)
return NULL
GGG = ?
(a)
while (!jobqueue->tail) /* wait */
(b)
/* no operation */
(c)
while (!jobqueue->tail) pthread_cond_wait(&jobqueue->cond_nonempty, &jobqueue->rwlock)
(d)
while (!jobqueue->tail) pthread_cond_broadcast(&jobqueue->cond_nonempty)
HHH = ?
(a)
pthread_cond_wait(&jobqueue->cond_nonempty, &jobqueue->rwlock)
(b)
pthread_cond_broadcast(&jobqueue->cond_nonempty)
KKK = ?
(a)
__FUTURE_RUNNING
(b)
__FUTURE_FINISHED
(c)
__FUTURE_TIMEOUT
(d)
__FUTURE_CANCELLED
(e)
__FUTURE_DESTROYED
LLL = ?
(a)
pthread_cond_broadcast(&task->future->cond_finished)
(b)
pthread_cond_wait(&task->future->cond_finished, &future->mutex)
延伸問題: