简体   繁体   English

带有信号冻结的Linux内核线程

[英]Linux Kernel Threads with semaphore freeze

I have two kernel threads and I am trying to print from these two threads in alternate fashion. 我有两个内核线程,我试图以替代方式从这两个线程中打印。 I am using semaphore to sync these two threads. 我正在使用信号量来同步这两个线程。

int kthread_1_function(void *data)
{
    while(1)
    {
        down(&lock);
        pr_alert("In Kernel Thread 1!!!\n");
        up(&lock);

        //kthread_should_stop must be used to check if this thread should be stopped
        if(kthread_should_stop())
            return 1;
    }

    return 0;
}

Similarly I have one more thread which is named as kthread_2_function. 同样,我还有一个名为kthread_2_function的线程。 In init module, I create these kernel threads ( kthread_run ) and cleanup_module stop these threads ( kthread_stop ). 在init模块中,我创建了这些内核线程( kthread_run ),并且cleanup_module停止了这些线程( kthread_stop )。

Following is my observation on various things I tried. 以下是我对尝试过的各种事情的观察。

  1. When I insert the module, prints are not alternate. 当我插入模块时,打印不是交替的。 I am assuming this is because by the time thread 2 acquires the lock, thread 1 reacquires the lock and prints again. 我假设这是因为线程2到获得锁时,线程1重新获得了锁并再次打印。
  2. When I use msleep(1000) or mdelay(1000) between down and up function calls in both threads I see alternate prints. 当我在两个线程的向下和向上函数调用之间使用msleep(1000)mdelay(1000)时,都会看到备用打印。
  3. When I use msleep(1000) after up function call in both threads again the prints are not alternate. 当我在两个线程中再次调用up函数后使用msleep(1000)时,打印不会交替显示。
  4. When I use mdelay(1000) after up function call in both threads I see alternate prints but when I remove the module complete system freezes 当我在两个线程中的up函数调用之后使用mdelay(1000) ,我会看到备用打印,但是当我删除模块时,整个系统将冻结

Can someone please help me understand above observations. 有人可以帮我理解上述观点吗?

Single semaphore won't give you the interleaving guarantee. 单个信号量不会给您提供交错保证。 You need two semaphores in order to enforce the interleaving. 您需要两个信号量才能执行交织。 Eg 例如

kthread_1_function:
            down(&lock1);
            pr_alert("In Kernel Thread 1!!!\n");
            up(&lock2);

kthread_2_function:
            down(&lock2);
            pr_alert("In Kernel Thread 2!!!\n");
            up(&lock1);

And you need to unblock semaphores before unload the modules to let the threads shutdown gracefully. 而且,在卸载模块之前,需要先解除阻塞信号量,以使线程正常关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM