linux2022
目的: 檢驗學員對 Linux 核心設計: 不僅是個執行單元的 Process 和 並行和多執行緒程式設計 的認知
作答表單:
1
(Linux 核心設計)1
在 Linux 核心設計: 不僅是個執行單元的 Process 提及 futex,我們可用來實作 lock,可見:
在 並行程式設計: POSIX Thread,提及案例: "Mutex and Semaphore" (你今天用對 mutex 了嗎?),提醒要留意細節。參考 man page pthread_mutex_unlock()
裏面提到:
If the mutex type is
PTHREAD_MUTEX_DEFAULT
, attempting to recursively lock the mutex results in undefined behavior. Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior. Attempting to unlock the mutex if it is not locked results in undefined behavior.
仔細地看 man page pthread_mutex_unlock()
會發現:
If the mutex type is
PTHREAD_MUTEX_ERRORCHECK
, then error checking shall be provided. If a thread attempts to relock a mutex that it has already locked, an error shall be returned. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error shall be returned.
我們需要在初始化 mutex 之際,就指定型態。
mu
是我們嘗試使用 futex 的多執行緒執行環境的實作,介面比照 POSIX Thread,針對 Linux/x86-64,程式碼可見: mu (部分遮蔽)
預期執行結果: (地址可能會不同)
請補完程式碼,使其符合預期。作答規範:
AAAA
, BBBB
, CCCC
都是表示方式,且都該使用 atomic_bool_cmpxchg
巨集DDDD
為整數延伸問題: