摘要:
本文以通俗的語言闡述了Contiki的兩個主要機制:事件驅(qū)動和protothread機制。
Contiki兩個主要機制:事件驅(qū)動和protothread機制,前者是為了降低功耗,后者是為了節(jié)省內(nèi)存。
一、事件驅(qū)動
嵌入式系統(tǒng)常常被設(shè)計成響應周圍環(huán)境的變化,而這些變化可以看成一個個事件。事件來了,操作系統(tǒng)處理之,沒有事件到來,就跑去休眠了(降低功耗),這就是所謂的事件驅(qū)動,類似于中斷。
二、protothread機制
2.1 概述
傳統(tǒng)的操作系統(tǒng)使用棧保存進程上下文,每個進程需要一個棧,這對于內(nèi)存極度受限的傳感器設(shè)備將難以忍受。protothread機制恰解決了這個問題,通過保存進程被阻塞處的行數(shù)(進程結(jié)構(gòu)體的一個變量,unsiged short類型,只需兩個字節(jié)),從而實現(xiàn)進程切換,當該進程下一次被調(diào)度時,通過switch(__LINE__)跳轉(zhuǎn)到剛才保存的點,恢復執(zhí)行。整個Contiki只用一個棧,當進程切換時清空,大大節(jié)省內(nèi)存。
2.2 特點
protothread(- Lightweight, Stackless Threads in C)最大特點就是輕量級,每個protothread不需要自己的堆棧,所有的protothread使用同一個堆棧,而保存程序斷點用兩個字節(jié)保存被中斷的行數(shù)即可。具體特點如下[1]:
Very small RAM overhead - only two bytes per protothread and no extra stacks
Highly portable - the protothreads library is 100% pure C and no architecture specific assembly code Can be used with or without an OS
Provides blocking wait without full multi-threading or stack-switching Freely available under a BSD-like open source license
protothread機制很早就有了,Contiki OS只要運用這種機制,protothread機制還可以用于以下情形[1]:
Memory constrained systems Event-driven protocol stacks Small embedded systems Sensor network nodes Portable C applications
2.3 編程提示
謹慎使用局部變量。當進程切換時,因protothread沒有保存堆棧上下文(只使用兩個字節(jié)保存被中斷的行號),故局部變量得不到保存。這就要求使用局部變量要特別小心,一個好的解決方法,使用局部靜態(tài)變量(加static修飾符),如此,該變量在整個生命周期都存在。
2.4 調(diào)度[2]
直接看原文吧。A protothread is driven by repeated calls to the function in which the protothread is running. Each time the function is called, the protothread will run until it blocks or exits. Thus the scheduling of protothreads is done by the application that uses protothreads.
如果還想進一步了解protothread,可以到[3]下載源碼,仔細研讀。
參考資料:
[1]Protothreads - Lightweight, Stackless Threads in C : http://www.sics.se/~adam/pt/
[2]About protothreads : http://www.sics.se/~adam/pt/about.html
[3]SourceForge--protothread : http://sourceforge.net/projects/protothread/ |