cgo 與 channel 的陷阱如何造成讀取 usb message 失敗 - lschyi

tags: COSCUP2020 中階 TR214

歡迎來到 https://hackmd.io/@coscup/2020 共筆

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

點擊本頁上方的 開始用 Markdown 一起寫筆記!
手機版請點選上方 按鈕展開議程列表。

請從這裡開始

講者使用很酷的人體工學鍵盤: ErgodoxTW

為了找到最適合自己的鍵盤按鍵自定義設定,需要從韌體去紀錄實際上按下了哪一個位置按鍵,而不是 ctrl, shift 的訊號

講者使用 QMK firmware,去接受到 usb keyboard 的 debug log ?

Log format

ErgoKB:4,6,0,1,40\n
  • col 4
  • row 6
  • released 0
  • layer 1
  • keycode 40

listener

使用 golang 實作一個 HID listener

v1

用 for loop 一直去讀 log,一個一個字元?
結果怪怪 der

cgo call 成本很高,講者做了一個 benchmark 差了幾乎將至 100 倍

解法:在 C 裡面多讀一點再丟到 golang listener

v2

跑起來卡住了?但每個 unit test 都過了

因為讀 HID 要一直 pulling ,其 timing 是很重要的
但 go channel 是有 lock 的,即便是 buffered channel
還是需要拿到 lock 才能寫入
因此整個程式 sequential 執行被影響到

結論

  • go 在開發 low level 的 app 目前不是最佳的
  • cgo 的 cost 不小,可以用適當的邏輯放到 C
  • channel 有一個 mutex lock,要拿到 lock 才能寫

工商

phoenix keyboard

Select a repo