分类: LINUX
2009-05-14 22:38:53
/*
* Reader-Writer是指保证一个Writer进程必须与其他进程互斥地访问共享对象的同步问题
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/sem.h>
struct semaphore sem_r;
struct semaphore sem_w;
int readcount = 0; /*表示正在读的进程数(可改成大于0的数)*/
int Read_thread(void *p);
int Write_thread(void *p);
int Read_thread(void *p)
{
p = p;
down(&sem_r); //使用读信号量
if(readcount == 0) //没有进程在读
down(&sem_w); //使用写信号量
readcount += 1;
up(&sem_r); //释放读信号量
printk("Lan is reading: %d\n", readcount);
down(&sem_r);
readcount -= 1;
printk("Read Finish\n\n");
if(readcount == 0)
up(&sem_w);
up(&sem_r);
return 0;
}
int Write_thread(void *p)
{
p = p;
down(&sem_w);
printk("Lan is writing\n");
printk("Write Finish\n\n");
up(&sem_w);
return 0;
}
static int lan_init(void)
{
printk("I am Coming\n");
init_MUTEX(&sem_r);
init_MUTEX(&sem_w);
kernel_thread(Write_thread, NULL, CLONE_KERNEL);
kernel_thread(Read_thread, NULL, CLONE_KERNEL);
kernel_thread(Write_thread, NULL, CLONE_KERNEL);
return 0;
}
static void lan_exit(void)
{
printk("Bye Bye\n");
}
module_init(lan_init);
module_exit(lan_exit);
MODULE_LICENSE("GPL");
#vim Makefile
obj-m += duxie.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean
注意:两个make前要先使用Tab键空出。
#sudo insmod duxie.ko
#dmesg
最后几行显示:
I am Coming
Lan is writing
Write Finish
Lan is reading: 1
Read Finish
Lan is writing
Write Finish