Linux设备驱动开发 - 内核线程和内核同步完成量completion示例

By: fulinux
E-mail: fulinux@sina.com
Blog: https://blog.csdn.net/fulinus
喜欢的盆友欢迎点赞和订阅!
你的喜欢就是我写作的动力!

在这里插入图片描述

概述

参考:linux中同步例子(完成量completion)
这是一个公交司机和售票员之间的线程调度,用于理解完成量,完成量是对信号量的一种补充,主要用于多处理器系统上发生的一种微妙竞争。在这里两个线程间同步,只有当售票员把门关了后,司机才能开动车,只有当司机停车后,售票员才能开门。

bus driver bus saleman waiting... I am waitting for saleman closed the door the door is closed! close the door you can go now! Ok, Let's go! Now~ driving stop the car Arrive the station. stoped car! open the door Ok, the door be opened! bus driver bus saleman

示例驱动

//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!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fulinux

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值