週三至工研院進行教育訓練,其中提到了「Linux pthread」的議題,並透過作業系統的觀念(sys_fork),簡單分析了一下為何 Linux pthread 是「bad」。在講解過程中,展示了一個 video surveillance 的應用程式,說明如何改用 event-driven / event-loop / feedback scheduling 的方式來取代傳統的 multi-threaded 架構。
此外,也提到 co-routine(協同式多工)的概念,建議可先行閱讀 [jserv] 兄的「使用 coroutine 實做 user-level thread」。
只以程式語言的技巧,來實作「多工」是一種很有用的做法,課程中,撰寫了一個「stack-based coroutine」的簡單實例,程式碼如下:
#include <stdio.h>
#include <pthread.h>
int count = 0;
int state = 0;
#define CHECK_POINT \
if (count > 3) { \
count = 0; \
state = 1; \
return; \
}
int foo(void)
{
static unsigned int i;
switch (state) {
case 0: goto L0;
case 1: goto L1;
}
L0: /* start of function */
i = 0;
while (1) {
i++;
CHECK_POINT;
L1:
printf("i = %d\n", i);
if (i == 30) break;
sleep(1);
}
printf("---------- foo exits ------------\n");
state = 0;
return 0;
}
void *counter(void *p)
{
while (1) {
count++;
sleep(1);
}
}
int main(void)
{
pthread_t tid;
pthread_create(&tid, NULL, &counter, NULL);
count = 0;
state = 0;
while (1) {
foo();
printf("Enter event looping ...\n");
};
}
Stack-based coroutine 是一種基於「function call」的「交錯執行」做法,最大的用途是,我們可以在「event handler」裡埋入「check point」,以達到「協同式」多工的效果。
以下是執行結果:$ ./co i = 1 i = 2 i = 3 i = 4 Enter event looping ... i = 5 i = 6 i = 7 i = 8 Enter event looping ... i = 9 i = 10 ... Enter event looping ... i = 29 i = 30 ---------- foo exits ------------ Enter event looping ... i = 1 i = 2 i = 3 Enter event looping ... i = 4非常有趣 ;-)
Jollen's Blog 使用 Github issues 與讀者交流討論。請點擊上方的文章專屬 issue,或 open a new issue
您可透過電子郵件 jollen@jollen.org,或是 Linkedin 與我連絡。更歡迎使用微信,請搜尋 WeChat ID:jollentw