By: fulinux
E-mail: fulinux@sina.com
Blog: https://blog.csdn.net/fulinus
喜欢的盆友欢迎点赞和订阅!
你的喜欢就是我写作的动力!
概述
参考:linux中同步例子(完成量completion)
这是一个公交司机和售票员之间的线程调度,用于理解完成量,完成量是对信号量的一种补充,主要用于多处理器系统上发生的一种微妙竞争。在这里两个线程间同步,只有当售票员把门关了后,司机才能开动车,只有当司机停车后,售票员才能开门。
示例驱动
//hello.c
#include <linux/module.h>
#include <linux/kthread.h>
static struct task_struct *ts_driver = NULL;
static struct task_struct *ts_saleman = NULL;
struct completion my_completion1;
struct completion my_completion2;
static int thread_driver(void *p)
{
printk(KERN_ALERT "Driver: I am waitting for saleman closed the door\n");
wait_for_completion(&my_completion1);
printk(KERN_ALERT "Driver: Ok, Let's go! Now~\n");
printk(KERN_ALERT "Driver: Arrive the station. stoped car!\n");
complete(&my_completion2);
return 0;
}
static int thread_saleman(void *p)
{
printk(KERN_ALERT "Saleman: the door is closed!\n");
complete(&my_completion1);
printk(KERN_ALERT "Saleman: you can go now!\n");
wait_for_completion(&my_completion2);
printk(KERN_ALERT "Saleman: Ok, the door be opened!\n");
return 0;
}
int init_module(void)
{
init_completion(&my_completion1);
init_completion(&my_completion2);
ts_driver = kthread_run(thread_driver, NULL, "%s", "busdriver");
ts_saleman = kthread_run(thread_saleman, NULL, "%s", "bussaleman");
return 0;
}
void cleanup_module(void)
{
printk("Goodbye Cruel World!\n");
}
MODULE_LICENSE("GPL");
Makefile文件
obj-m := hello.o
SRC := $(shell pwd)
all:
$(MAKE) -C $(KERNEL_SRC) M=$(SRC)
modules_install:
$(MAKE) -C $(KERNEL_SRC) M=$(SRC) modules_install
clean:
rm -f *.o *~ core .depend .*.cmd *.ko *.mod.c
rm -f Module.markers Module.symvers modules.order
rm -rf .tmp_versions Modules.symvers
运行演示
root@msm8937:~# insmod hello.ko
[ 6560.041259] Driver: I am waitting for saleman closed the door
[ 6560.042540] Saleman: the door is closed!
[ 6560.042545] Saleman: you can go now!
[ 6560.052027] Driver: Ok, Let's go! Now~
[ 6560.055457] Driver: Arrive the station. stoped car!
[ 6560.059166] Saleman: Ok, the door be opened!