下面是一个内核模块多线程的例子,不过这个模块执行的时候你卸载不了
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define DEBUG
#ifdef DEBUG
#define DBG(x...) printk(x)
#else
#define DBG(x...)
#endif
typedef struct kbuff_list
{
char buff_node[20];
int flag;
struct kbuff_list *next;
}KBUFF;
KBUFF *pread_kbuff,*pirq__kbuff;
unsigned long list_cnt;
static struct task_struct *ret;
struct semaphore sem;
static void readThread(void){
KBUFF *p1;
while(1){
down(&sem);
if(pread_kbuff !=NULL){
p1=pread_kbuff;
DBG("the pread_kbuff->buff_node is %s,flag is %d\n",pread_kbuff->buff_node,pread_kbuff->flag);
pread_kbuff=pread_kbuff->next;
kfree(p1);
}
}
// DBG("the %s is end\n",__FUNCTION__);
}
static void init_kbuff_list(void){
list_cnt=0;
pread_kbuff=pirq__kbuff=NULL;
sema_init(&sem, 0);
}
static void __init init_funct(void)
{
KBUFF *p1,*p2;
char kbuffer[20]="zhangfei is best";
init_kbuff_list();
ret = kthread_run(readThread, NULL, "thread_func2");
if (!IS_ERR(ret))
{
printk("kthread_create done\n");
}
else
{
printk("kthread_create error\n");
}
list_cnt++;
while(1){
p2=p1=(KBUFF *)kmalloc(sizeof(KBUFF),GFP_KERNEL);
strcpy(p1->buff_node,kbuffer);
p1->flag=list_cnt;
if(list_cnt==1 || pread_kbuff == NULL){
pirq__kbuff=pread_kbuff=p1;
printk("the code get %ldth here\n",list_cnt);
}
else
pirq__kbuff->next=p1;
p1->next=NULL;
pirq__kbuff=p1;
up(&sem);
list_cnt++;
if(list_cnt==65536)
list_cnt=2;
DBG("this is the %s-> %d.the flag is %ld\n",__FUNCTION__,__LINE__,list_cnt);
#if 0
ret = pthread_create(&id1, NULL, (void*)readThread, NULL);
if(ret != 0) {
printf("\n the readThread_create is failed!\n");
}
ret=pthread_join(id1,NULL);
if(ret!=0){
perror("Thread join failed");
exit(EXIT_FAILURE);
}
#endif
}
}
static void __init clean_funct(void){
KBUFF *p1;
while(pread_kbuff !=NULL){
p1=pread_kbuff;
DBG("the pread_kbuff->buff_node is %s,flag is %d\n",pread_kbuff->buff_node,pread_kbuff->flag);
pread_kbuff=pread_kbuff->next;
kfree(p1);
}
kthread_stop(ret);
}
module_init(init_funct);
module_exit(clean_funct);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Bob Wang");
MODULE_DESCRIPTION("Dpram Driver Module for NCM Board");
上面这个程序中使用了内核线程和内核的信号量机制,还有内核的kmalloc等。。。
阅读(313) | 评论(0) | 转发(0) |