驱动代码:
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/semaphore.h> //信号量有关的头文件
#define N 15
MODULE_LICENSE("GPL");
static unsigned count=0,num=0;
#define DECLARE_MUTEX(name) \
struct semaphore name = __SEMAPHORE_INITIALIZER(name, 1)//这一行在头文件semaphore.h中定义
#define init_MUTEX_LOCKED(sem) sema_init(sem, 0) //宏定义,头文件semaphore.h 定义sema_init(sem, 0)
struct semaphore sem_2;
DECLARE_MUTEX(sem_1);/*init 1*/
int ThreadFunc1(void *context)
{
char *tmp=(char*)context;
while(num<N){
down(&sem_1);
printk("<2>" "%s\tcount:%d\n",tmp,count++);
num++;
up(&sem_2);
}
return 0;
}
int ThreadFunc2(void *context)
{
char *tmp=(char*)context;
while(num<N){
down(&sem_2); //第一次执行,等待资源释放
printk("<2>" "%s\tcount:%d\n",tmp,count--);
num++;
up(&sem_1);
}
return 0;
}
static __init int semaphore_init(void)
{
char *ch1="this is first thread!";
char *ch2="this is second thread!";
init_MUTEX_LOCKED(&sem_2);/*init 0*/
kernel_thread(ThreadFunc1,ch1,CLONE_KERNEL);
kernel_thread(ThreadFunc2,ch2,CLONE_KERNEL);
return 0;
}
static void semaphore_exit(void)
{
}
module_init(semaphore_init);
module_exit(semaphore_exit);
MODULE_AUTHOR("Mike Feng");
执行结果:
总结:
信号量一般这样被使用
/*定义信号量
DECLARE_MUTEX(mount_sem);
down(&mount_sem);/*获得信号量,保护临界区*/
critical section /*临界区*/
up(&mount_sem);/释放信号量
如果信号量被初始化为0,则它可以用于同步,同步意味着一个执行单元的继续执行需等待另一个执行单元完成,保证执行的先后顺序。