linux顺序锁

#include<linux/fs.h>
#include<linux/sched.h>
#include<linux/kthread.h>
#include<linux/module.h>
#include<linux/delay.h>
#include<linux/seqlock.h>//顺序锁头文件
static int i=0,j=100;//一个线程从0开始加,一个线程从100开始加
struct task_struct *MyThread1=NULL;//线程1
struct task_struct *MyThread2=NULL;//线程2
static int myVar = 0;//定义变量
static int count = 0;
seqlock_t lock;//定义顺序锁
static void setMyVar(int input)//写变量
{
        write_seqlock(&lock);//加顺序写锁
        //临界区
        if(count)//count=1进入
        {
            printk("busy setMyVar\n");
        }
        count++;//conut=1
    myVar = input;//写变量,将input值赋值给myVar
    printk("setMyVar is %d\n",myVar);//打印写的变量值
    write_sequnlock(&lock);//释放顺序写锁
    count--;//count=0;
}
static int getMyVar(void)//读变量
{
    int res = 0;//用于读取变量myVar的值
    unsigned long seq;//顺序锁中的顺序计数器
    do
    {
            seq=read_seqbegin(&lock);//读取顺序号,如果是奇数,说明正在进行写操作,处理器就等待,如果不是奇数,就返回读到的顺序号
            //临界区
            if(count)
            {
                printk("busy setMyVar\n");
            }
            count++;
        res = myVar;//读变量,将myVar变量值赋值给res
        printk("getMyVar is %d\n",res);//打印读取的变量res的值
    }while(read_seqretry(&lock,seq));//检测读的数据有没有效,如果顺序号跟一开始的不一致,就返回1,说明修改了临界区,需要重新读数据
    count--;//count=0;
    return 0;
}
static int print1(void *data)//线程1打印函数
{
    while(!kthread_should_stop())//判断该线程是否停止,若线程未停止则进入
    {
        printk("this is thread1......\n");//提示这是线程1
        getMyVar();//读变量
        setMyVar(i);//写变量
        ssleep(1);//沉睡1秒
        i++;//i+1
    }
    return 0;
}
static int print2(void *data)//线程2打印函数
{
    while(!kthread_should_stop())//判断该线程是否停止,若线程未停止则进入
    {
        printk("this is thread2......\n");//提示这是线程2
        getMyVar();//读变量
        setMyVar(j);//写变量
        ssleep(1);//沉睡1秒
        j++;//j+1
    }
    return 0;
}

static int __init hello_init(void){//模块加载入口函数
    seqlock_init(&lock);//顺序锁初始化
    MyThread1 = kthread_run(print1,NULL,"mythread1");//创建线程1,名字是mythread1,调用的函数是print1函数
    MyThread2 = kthread_run(print2,NULL,"mythread2");//创建线程2,名字是mythread2,调用的函数是print2函数
    return 0;
}
static void __exit
hello_exit(void){//模块退出函数
    if(MyThread1)//如果线程1还存在,那么就停止该线程
    {
        printk("kthread1 stop....\n");//提示即将停止线程1
        kthread_stop(MyThread1);//调用kthread_stop函数停止线程1
        MyThread1=NULL;//将结构体指针MyThread1指向空
    }
    if(MyThread2)//如果线程2还存在,那么就停止该线程
    {
        printk("kthread2 stop....\n");//提示即将停止线程2
        kthread_stop(MyThread2);//调用kthread_stop函数停止线程2
        MyThread2=NULL;//将结构体指针MyThread2指向空
    }
        
}
module_init(hello_init);//模块加载
module_exit(hello_exit);//模块退出
MODULE_LICENSE("GPL");//模块许可证
MODULE_AUTHOR("Valerie Henson [email protected]");//模块作者信息
MODULE_DESCRIPTION("\"rwlock\" minimal module");//模块描述
MODULE_VERSION("printk");//模块版本

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。