21.用鎖實現終端輸出

本文就是利用上一篇博文的 鎖 ,來實現終端輸出,避免產生競爭條件。

新建一個文件 console.c。
console.c

#include "console.h"
#include "../lib/kernel/print.h"
#include "../lib/std_int.h"
#include "../thread/sync.h"
#include "../thread/thread.h"
static struct lock console_lock;    // 控制檯鎖

/* 初始化終端 */
void console_init() {
  lock_init(&console_lock); 
}

/* 獲取終端 */
void console_acquire() {
   lock_acquire(&console_lock);
}

/* 釋放終端 */
void console_release() {
   lock_release(&console_lock);
}

/* 終端中輸出字符串 */
void console_put_str(char* str) {
   console_acquire(); 
   put_str(str); 
   console_release();
}

/* 終端中輸出字符 */
void console_put_char(uint8_t char_asci) {
   console_acquire(); 
   put_char(char_asci); 
   console_release();
}

/* 終端中輸出16進制整數 */
void console_put_int(uint32_t num) {
   console_acquire(); 
   put_int(num); 
   console_release();
}

在main.c 中調用終端用鎖來封裝的一些函數。

main.c

#include "../lib/kernel/print.h"
#include "my_interrupt.h"
#include "../device/timer.h"
#include "debug.h"
#include "memory.h"
#include "../thread/thread.h"
#include "init.h"

void k_thread_a(void*);
void k_thread_b(void*);

int main(void) {
	put_str("tt i am kernel !\n");
	init_all();	
	
	thread_start("k_thread_a", 31, k_thread_a, "argA ");
	thread_start("k_thread_b", 8, k_thread_b, "argB ");
	
	intr_enable();	// 打開中斷,使時鐘中斷起作用
	while(1){		
		console_put_str("Main ");	
	}
	return 0;
}

/* 在線程中運行的函數 */
void k_thread_a(void* arg) {     
/* 用void*來通用表示參數,被調用的函數知道自己需要什麼類型的參數,自己轉換再用 */
   char* para = arg;
   while(1) {
		console_put_str(para);
   }
}

/* 在線程中運行的函數 */
void k_thread_b(void* arg) {     
/* 用void*來通用表示參數,被調用的函數知道自己需要什麼類型的參數,自己轉換再用 */
   char* para = arg;
   while(1) {
      console_put_str(para);
   }
}
發佈了117 篇原創文章 · 獲贊 19 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章