#include<linux/init.h>
#include<linux/module.h>
#include<linux/sched.h>
//#include<linux/sem.h>
#include<linux/semaphore.h> //2.6.28
MODULE_LICENSE("Dual BSD/GPL");
int num[2][5]={
{0,2,4,6,8},
{1,3,5,7,9}
};
struct semaphore sem_first;
struct semaphore sem_second;
int thread_print_first(void *);
int thread_print_second(void *);
int thread_print_first(void *p)
{
int i;
int *num=(int *)p;
for(i=0;i<5;i++) {
down(&sem_first);
printk(KERN_INFO"Hello World:%d/n",num[i]);
up(&sem_second);
}
return 0;
}
int thread_print_second(void *p)
{
int i;
int *num=(int *)p;
for(i=0;i<5;i++) {
down(&sem_second);
printk(KERN_INFO"Hello World:%d/n",num[i]);
up(&sem_first);
}
return 0;
}
static int hello_init(void)
{
printk(KERN_ALERT"Hello World enter/n");
init_MUTEX(&sem_first);
init_MUTEX_LOCKED(&sem_second);
kernel_thread(thread_print_first,num[0],CLONE_KERNEL);
kernel_thread(thread_print_second,num[1],CLONE_KERNEL);
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT"hello world exit/n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("Niu Tao");
MODULE_DESCRIPTION("A simple hello world Module");
MODULE_ALIAS("a simplest module");
Makefile:
obj-m :=hello.o
CURRENT_PATH := $(shell pwd)
LINUX_KERNEL := $(shell uname -r)
LINUX_KERNEL_PATH := /usr/src/linux-headers-$(LINUX_KERNEL)
all:
make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
clean:
rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions Module.symvers .Makefile.swp
功能:使用信号量实现数据的顺序打印
运行结果:
[ 7538.928624] Hello World enter
[ 7538.928846] Hello World:0
[ 7538.940529] Hello World:1
[ 7538.940584] Hello World:2
[ 7538.940840] Hello World:3
[ 7538.940844] Hello World:4
[ 7538.941038] Hello World:5
[ 7538.941042] Hello World:6
[ 7538.941218] Hello World:7
[ 7538.941222] Hello World:8
[ 7538.941408] Hello World:9
[ 7562.273176] hello world exit
http://blogold.chinaunix.net/u2/73528/showart_1212309.html