在加载函数中,完成一些初始化的工作,并分别创建了5个生产者线程和消费者线程。kernel_thread函数的第一个参数是所所创建线程要做的动作;通过第二个参数传递i变量。
01 | static int __init np_nc_init( void ) |
02 | { |
03 | int i; |
04 |
05 | printk( "np_nc module is working..\n" ); |
06 | in=out=0; |
07 | cflag=0; |
08 | init_MUTEX(&mutex); |
09 | sema_init(&s1,BUF_NUM); |
10 | sema_init(&s2,0); |
11 |
12 | for (i=0;i< N;i++) |
13 | { |
14 | index[i]=i+1; |
15 | kernel_thread(productor_thread,&(index[i]),CLONE_KERNEL); |
16 | kernel_thread(consumer_thread,&(index[i]),CLONE_KERNEL); |
17 | } |
18 |
19 | return 0; |
20 | } |
在生产者函数中,PNUM是每个生产者要生产货物的数量。语句buf[in]=i*100+(PNUM-p_num+1)即是产生货物的过程。
01 | int productor_thread( void *p) |
02 | { |
03 | int i=*( int *)p; |
04 | int p_num=PNUM; |
05 |
06 | while (p_num) |
07 | { |
08 | if ((s1.count)<=0) |
09 | { |
10 | printk( "[producer %d,%d]:I will be waiting for producting..\n" ,i,s1.count); |
11 | } |
12 | down(&s1); |
13 | down(&mutex); |
14 | buf[in]=i*100+(PNUM-p_num+1); |
15 | printk( "[producer %d,%d]:I producted a goods \"%d\" to buf[%d]..\n" ,i,s1.count,buf[in],in); |
16 | in=(in+1)%BUF_NUM; |
17 | up(&mutex); |
18 | up(&s2); |
19 | p_num--; |
20 | } |
21 | return 0; |
22 | } |
在消费者函数中,通过一个全局变量CNUM来控制消费者总共的消费次数。
01 | int consumer_thread( void *p) |
02 | { |
03 | int i=*( int *)p; |
04 | int goods; |
05 |
06 | while (cflag!=CNUM) |
07 | { |
08 | if ((s2.count)<=0) |
09 | { |
10 | printk( "[consumer %d,%d]:I will be waiting for goods..\n" ,i,s2.count); |
11 | } |
12 | down(&s2); |
13 | down(&mutex); |
14 | goods=buf[out]; |
15 | printk( "[consumer %d,%d]:I consumed a goods \"%d\" from buf[%d]..\n" ,i,s2.count,goods,(out%BUF_NUM)); |
16 | out=(out+1)%BUF_NUM; |
17 | up(&mutex); |
18 | up(&s1); |
19 | cflag++; |
20 | } |
21 | return 0; |
22 | } |