全部博文(573)
分类: LINUX
2015-12-04 10:32:06
这是一个公交司机和售票员之间的线程调度,用于理解完成量,完成量是对信号量的一种补充,主要用于多处理器系统上发生的一种微妙竞争
在这里两个线程间同步,只有当售票员把门关了后,司机才能开动车,只有当司机停车后,售票员才能开门。
#include
#include
#include
#include
#include
MODULE_LICENSE("Dual BSD/GPL");
struct completion my_completion1;
struct completion my_completion2;//定义了两个完成量
int thread_dirver(void *);
int thread_saleman(void *);
int thread_driver(void *p)//司机线程
{
printk(KERN_ALERT"DRIVER:I AM WAITING FOR SALEMAN CLOSED THE DOOR/n");
wait_for_completion(&my_completion1);//等待完成量completion1
printk(KERN_ALERT"DRIVER:OK , LET'S GO!NOW~/n");
printk(KERN_ALERT"DRIVER:ARRIVE THE STATION.STOPED CAR!/n");
complete(&my_completion2);//唤醒完成量completion2
return 0;
}
int thread_saleman(void *p)//售票员线程
{
printk(KERN_ALERT"SALEMAN:THE DOOR IS CLOSED!/n");
complete(&my_completion1);//唤醒完成量completion1
printk(KERN_ALERT"SALEMAN:YOU CAN GO NOW!/n");
wait_for_completion(&my_completion2);//等待完成量completion2
printk(KERN_ALERT"SALEMAN:OK,THE DOOR BE OPENED!/n");*/
return 0;
}
static ssize_t change_runmode(struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
char *tail;
int op;
op = simple_strtol(buf, &tail, 10);
switch(op) {
case 0:
printk("turn off gps module/n");
kernel_thread(thread_saleman,NULL,CLONE_KERNEL);//创建了两个内核线程,
msleep(100); //此处最好加入一个delay,不然的话2个线程的执行顺序无法保障
kernel_thread(thread_driver,NULL,CLONE_KERNEL);
break;
case 1:
printk("turn on gps module/n");
break;
default:
printk(KERN_ERR " Unknown operation %d/n", op);
}
return count;
}
static struct bin_attribute ublox_mode_attr = {
.attr = {
.name = "ublox",
.owner = THIS_MODULE,
.mode = S_IRUGO | S_IWUGO,
},
.size = 4,
//.read = show_runmode,
.write = change_runmode,
};
static int hello_init(void)
{
int ret;
printk(KERN_ALERT"Hello everybody~/n");
init_completion(&my_completion1);
init_completion(&my_completion2);//初始化完成量
ret = sysfs_create_bin_file(&(module_kset->kobj), &ublox_mode_attr);
if (ret) {
printk(KERN_ERR " Failed to create sys file/n");
return -ENOMEM;
}
// kernel_thread(thread_saleman,NULL,CLONE_KERNEL);//创建了两个内核线程,
//kernel_thread(thread_driver,NULL,CLONE_KERNEL);
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT"sunqidong Goodbye everybody~/n");
sysfs_remove_bin_file(&(module_kset->kobj), &ublox_mode_attr);
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("SUN");
MODULE_DESCRIPTION("A simple completion Module");
执行结果:
Hello everybody~
DRIVER:I AM WAITING FOR SALEMAN CLOSED THE DOOR
SALEMAN:THE DOOR IS CLOSED!
SALEMAN:YOU CAN GO NOW!
DRIVER:OK , LET'S GO!NOW~
DRIVER:ARRIVE THE STATION.STOPED CAR!
SALEMAN:OK,THE DOOR BE OPENED!
Goodbye everybody~