并发控制

1. 定义:
文件: <asm/semaphore.h>
数据类型: struct semaphore
直接创建:
void sema_init(struct semaphore *sem, int val); /* 其中val是信号量的初始值 */

辅助宏:
DECLARE_MUTEX(name); /* 把一个称为name的信号量变量初始化为1 */
DECLARE_MUTEX_LOCKED(name); /* 把一个称为name的信号量变量初始化为0 */


动态分配:
/* 用于运行时的初始化 */
void init_MUTEX(struct semaphore *sem);
void init_MUTEX_LOCKED(struct semaphore *sem);


在Linux世界中, P函数被称为down, 指的是该函数减小了信号量的值, 它也许会将调用者置于休眠状态, 然后等待信号量变得可用, 之后再授予调用者对被保护资源的访问权限. down函数有三个版本:
/* 减小信号量的值, 并在必要时一直等待 */
void down(struct semaphore *sem);

/* 可中断版本, 常用 */
void down_interruptible(struct semephore *sem);
作为通常规则, 我们不应该使用非中断版本.
使用该函数, 如果操作被中断, 该函数会返回非0值, 而调用者不会拥有该信号量.
因此对该函数的正确使用需要始终检查返回值, 并做出相应的响应.

/* 永远不会休眠, 如信号量在调用时不可获得, 立即返回非0值 */
void down_trylock(struct semaphore *sem);

当一个线程成功调用down函数的某个版本之后, 就称为该线程拥有了该信号量, 可以访问被该信号量保护的临界区. 当互斥操作完成后, 必须释放该信号量.
Linux的V函数是up:
/* 调用up之后, 调用者不再拥有该信号量 */
void up(struct semaphore *sem);

2. 举例:
我们拥有一个共享数据结构:
struct st_data
{
    char name[32];
    char data[128];
    int data_len;
};

这个数据结构被多个进程同时访问.
为了避免这些进程在访问该结构时产生竞态, 我们在该结构的底部为其加上信号量:
struct st_data
{
    char name[32];              /* name */
    char data[128];              /* data */
    int data_len;                  /* data length */
    struct semaphore sem; /* semaphore */
};

信号量在使用前必须进行初始化, 而且是在共享数据其他部分可用前初始化. 因此, 我们在其他数据赋值之前调用init_MUTEX, 否则会建立一个竞态, 即在信号量准备好之前, 有代码可能会访问它们.

st_data data;
init_MUTEX(&data->sem);
setup_data(&data); /* 初始化数据 */
...
...


接下来, 我们必须仔细检查代码, 确保在不拥有该信号量的时候不会访问data数据结构. 例如, 在data_write的开始处加入:
if (down_interruptible(&data->sem))   
    return -ERESTARTSYS;

这是检查down_interruptible的返回值, 如果返回非0值, 说明操作被中断. 这种情况下, 通常要做的工作是返回-ERESTARTSYS. 在得到这个返回值后, 内核会从头重新启动该调用, 或者将该错误返回给用户.
如果我们返回-ERESTARTSYS, 则必须首先撤销已经做出的修改, 这样, 系统调用才可正确重试. 如果无法撤销这些操作, 则应该返回-EINTR, 表明中断.

不管data_write能否完成其他工作, 它都必须释放信号量:
out:
    up(&data->sem);
    return retval;


在data_write中有几个地方可能会产生错误, 包括内存分配失败等. 在这些情况下, 代码会执行goto out, 确保正确的完成信号量的释放工作.
 
接下来用例子来说明一下,休眠与等待队列/信号量的用法!
首先要了解信号量的作用:消除竞态,竞态的产生是由于多进程并发(简单的说就是多个线程访问共同的资源,,出现竞态有可能会将先访问的线程数据淹没掉).通常信号量是存在一个数据链里面.同时我们把多线程访问共同资源时,建立一个临界区.对于LINUX中是会存在的, 因为它是多线程(任务)的操作系统.因为是并发运行的互相不干扰!存在数据共享,数据交换/通信!
当然消除的方法有多种!这里只说一下信号量,后面再讲自旋锁及complete.信号量的用法,实际上也是原子操作不同而已!才会有这两个不同的称呼!
这是一个读写的过程! 上代码了!下面是驱动代码!
首先说一下程序的思路!
当用户程序来读的时候,只要没有执行写的操作,那么读的进程会进入休眠(相对来说此操作被阻塞),这时,我们可以在此程序中进行扩展,如:某寄存器没有数据就不执行读的操作(这样对系统资源可以节约).但是在此之前对这个程序的读写是有条件的必须要获得该数据的信号量,才能访问下面的资源(这样就消除了竞态),此时其它的想访问的进程只能在外等待(进程被挂起).这里没有用到一个库作为数据链表!只是单个的数据与信号量!
 
阻塞操作是指,在执行设备操作时,若不能获得资源,则进程挂起直到满足可操作的条件再进行操作。
 
非阻塞操作的进程在不能进行设备操作时,并不挂起。被挂起的进程进入sleep状态,被从调度器的运行队列移走,直到等待的条件被满足。
这时候我们就自然的引入到了一个等待队列等待进程醒来.队列的作用是让我们进程进入休眠后,将其它唤醒一数据链表,好让我们找到它的位置将其唤醒.
/*
*      file name:  "signel"
*
*      author    :  "kang"
*
*
*      data       : 2009-3-11
*/
#include <linux/kernel.h>
#include <linux/config.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/wait.h>
#include <linux/errno.h>
#include <linux/devfs_fs_kernel.h>
#include <asm/semaphore.h>
#include <asm/uaccess.h>
#define  DEV_NAME  "signel"
#define  DEV_ID 110
static int flags=0;
static DECLARE_WAIT_QUEUE_HEAD(in);
static int arry[4];
struct semaphore sem;
static int signel_write(struct file *file,const char __user * buf,size_t count,loff_t *off)
{ printk("%i,%s/n",current->pid,current->comm);
  flags=1;
  if(down_interruptible(&sem))       //获取访问数据的信号量,将其它要访问者致于休眠等待.
    { return -ERESTARTSYS;
       }
  printk("write data....!!!/n");
  if(copy_from_user(&arry,buf,count)) // 开始对数据访问(传输),此过程中其它访问者都在外候着.
   { up(&sem);
      return -EFAULT;
      }
  wake_up_interruptible(&in);    //解除read阻塞(唤醒).
  up(&sem);                                   //将那些要访问arry[4]数据的进程唤醒.
  return count;
    }  
static int signel_read(struct file *file,char __user * buf,size_t count,loff_t *off)
{  printk ("%i,%s/n",current->pid,current->comm);
   if(wait_event_interruptible(in,flags!=0))      这条语句与下面down_interruptible()尽量不要同时出现在一个程序段里面,很容易出现死锁.这时,是两个阻塞事件一起出现在此!
     { return -ERESTARTSYS;
        }
   if(down_interruptible(&sem))
    { return -ERESTARTSYS;
       }
   flags=0;
   printk("read data....!!!/n");
   if(copy_to_user(buf,&arry,count))
    { up(&sem);
      return  -EFAULT;
       }
   up(&sem);
   return count;
    }
static struct file_operations signel_test = {
 .write  =   signel_write,
 .read   =   signel_read,
};
static int __init init_signel(void)
{ int ret;
  sema_init(&sem,1); /* 或者用init_MUTEX(&sem) 初始化并声明为互斥(实际上也就是将信号量为“1”也就是它互斥模式)*/
  ret=register_chrdev(DEV_ID,DEV_NAME,&signel_test);
  if(ret<0)
   { printk("registre is fail!!/n");
      return ret;
        }
   else
    { printk("registre is scuss!!/n");
      devfs_mk_cdev(MKDEV(DEV_ID,0),S_IFCHR | S_IRUSR | S_IWUSR,"signel");
   return 0;
       }
   return 0;
      }
static void __exit exit_signel(void)
{ unregister_chrdev(DEV_ID,DEV_NAME);
  devfs_remove(DEV_NAME);
      }
module_init(init_signel);
module_exit(exit_signel);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("KANG");
MODULE_DESCRIPTION("SIGNE");
 
这里有几点要说明一下INIT的问题!
首先我们定义一个信号量(sem),程序当中定义一个库结构的变量-->static struct semaphore (sem)
对于在获取信号量的几个函数:
down(struct semaphore *sem)
down_interruptible(struct semaphore *sem)
down_trylock(struct semaphore *sem)
down(struct semaphore *sem)不能被信号中断,也就是说当获取信号量在等待的进程是不能中断的,此时会进入休眠的状态.
 
down_interruptible(struct semaphore *sem)这个就可以被信号中断,一般的我们都采用此用法,中断之后会返回一个非"0"值
这时我们要返回一个 -ERESTARTSYS,这个东西比较有用,内核会检测到此值之后.会有两种动作要么就重新启动该调用动作,要么就将错误报告给用户层.
 
down_trylock(struct semaphore *sem)这个永远不休眠!现在我还不知道其用法,稍后补上.
 
有获取也有释放动作!都是用一个函数up(struct semaphore *sem),这一点比较重要当获取信号量时,不管其中的程序操作成功/失败,都得要释放信号量.要不然,应
进程一直占用这个资源!
 
下面是休眠讲解
以下几个是简单休眠的函数!

wait_event(queue,condition)/*不可中断休眠,不推荐*/
wait_event_interruptible(queue,condition)/*推荐,返回非零值意味着休眠被中断,且驱动应返回 -ERESTARTSYS*/
wait_event_timeout(queue,condition,timeout)
wait_event_interruptible_timeout(queue,condition,timeout)
/*有限的时间的休眠;若超时,则不管条件为何值返回0,*/

 

唤醒休眠进程的函数称为 wake_up,形式如下:

voidwake_up(wait_queue_head_t*queue);
voidwake_up_interruptible(wait_queue_head_t*queue);

用写程序去唤醒读程序,同时再写该数据时首先和上面说的一样要获取该数据的信号量.然后地能写入数据.

发下为两个DOME!

--------------------read----------------------

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define DEV_NAME "/dev/signel"
int main()
{ int fd,a;
  fd=open(DEV_NAME,O_RDWR);
  if (fd<0)
   { printf ("the file opened is fail!!!/n");
     }
  else
   { printf ("the file opened is scuss!!/n");
      read(fd,&a,sizeof(a));
   printf("a=%d/n",a);
      }
  close (fd);
  printf("the file is closed/n");
   }

--------------------------write------------------------

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define DEV_NAME "/dev/signel"
int main()
{ int fd,ret;
  int a=01;
  fd=open(DEV_NAME,O_RDWR);
  if(fd<0)
   { printf("opened is fail!!/n");
      }
   else
    { printf("open is scuss!!!/n");
      printf("writr a=%d/n",a);
      write(fd,&a,sizeof(a));
    }
   close(fd);
   printf("closed the file!!/n");
}
下面是在2440上面运行的结果

[root@(none) tmp]# insmod signel.ko
Using signel.ko
registre is scuss!!

尝试读的DOME结果与我们一致!进程被挂起在等待中!不能向下了!

[root@(none) tmp]# ./read
the file opened is scuss!!  
434,read             此处打印出进程ID号和命令 ID=434 COMMAND=read

再用ctrl+c结束!准备写入数据,进程停止此处

[root@(none) tmp]#

写入数据

[root@(none) tmp]# ./write
open is scuss!!!
436,write
write data....!!!
writr a=1
closed the file!!

再读结果与我们一致

[root@(none) tmp]# ./read
the file opened is scuss!!
437,read
read data....!!!
a=1
the file is closed !!

再验证,再读!末读到数据,进程被挂起!

[root@(none) tmp]# ./read
the file opened is scuss!!
438,read

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值