当前页面为 开发中 版本,查看特定版本的文档,请在页面左下角的下拉菜单中进行选择。

Basic: Synchronization

1 功能概述

一个简单的应用程序,演示了内核的基本功能。两个线程(A和B)轮流向控制台打印问候消息,并使用睡眠请求和信号量来控制消息的生成速率。这说明了内核调度,通信,而且时间安排是正确的。

2 环境要求

  • Board: pan108xxa1_evb / pan108xxa3_evb / pan108xxb1_evb / pan108xxb5_evb

  • UART: 将 P00 与 TX0 引脚接在一起,P01 与 RX0 引脚接在一起,在 PC 上打开终端工具(如 SecureCRT),波特率设置为 921600

3 编译和烧录

例程位置:zephyr\samples_panchip\basic\synchronization

使用 ZAL 工具可以对其进行编译、烧录、打开 VS Code 调试等操作。关于 ZAL 工具的详细介绍请参考:Zephyr APP Launcher 工具介绍

4 演示说明

下载后,串口工具中看到程序成功运行,两个线程 threadAthreadB 交替打印 Log 信息

*** Booting Zephyr OS version 2.7.0  ***
thread_a: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_b: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_a: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_b: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_a: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_b: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_a: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_b: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_a: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_b: Hello PAN1080 from cpu 0 on pan108xxb5_evb!
thread_a: Hello PAN1080 from cpu 0 on pan108xxb5_evb!

5 开发说明

建立两个线程

	k_thread_create(&threadA_data, threadA_stack_area,
			K_THREAD_STACK_SIZEOF(threadA_stack_area),
			threadA, NULL, NULL, NULL,
			PRIORITY, 0, K_FOREVER);
	k_thread_name_set(&threadA_data, "thread_a");

	k_thread_create(&threadB_data, threadB_stack_area,
			K_THREAD_STACK_SIZEOF(threadB_stack_area),
			threadB, NULL, NULL, NULL,
			PRIORITY, 0, K_FOREVER);
	k_thread_name_set(&threadB_data, "thread_b");

轮询调度线程信号量

/*
 * @param my_name      thread identification string
 * @param my_sem       thread's own semaphore
 * @param other_sem    other thread's semaphore
 */
void helloLoop(const char *my_name,
	       struct k_sem *my_sem, struct k_sem *other_sem)
{
	const char *tname;
	uint8_t cpu;
	struct k_thread *current_thread;

	while (1) {
		/* take my semaphore */
		k_sem_take(my_sem, K_FOREVER);

		current_thread = k_current_get();
		tname = k_thread_name_get(current_thread);
		/* say "hello" */
		if (tname == NULL) {
			printk("%s: Hello World from cpu %d on %s!\n",
				my_name, cpu, CONFIG_BOARD);
		} else {
			printk("%s: Hello World from cpu %d on %s!\n",
				tname, cpu, CONFIG_BOARD);
		}

		/* wait a while, then let other thread have a turn */
		k_busy_wait(100000);
		k_msleep(SLEEPTIME);
		k_sem_give(other_sem);
	}
}

6 RAM/Flash资源使用情况

Memory region         Used Size  Region Size  %age Used
FLASH:       16968 B       384 KB      4.32%
SRAM:        7824 B        64 KB     11.94%