信号量同步 semaphore

驱动代码:

#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,则它可以用于同步,同步意味着一个执行单元的继续执行需等待另一个执行单元完成,保证执行的先后顺序。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值