gpt4 book ai didi

c - 带有信号量卡住的 Linux 内核线程

转载 作者:行者123 更新时间:2023-11-30 17:29:04 26 4
gpt4 key购买 nike

我有两个内核线程,我正在尝试以交替方式从这两个线程进行打印。我正在使用信号量来同步这两个线程。

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;
}

类似地,我还有一个名为 kthread_2_function 的线程。在 init 模块中,我创建这些内核线程 (kthread_run),并通过 cleanup_module 停止这些线程 (kthread_stop)。

以下是我对我尝试过的各种事情的观察。

  1. 当我插入模块时,打印不交替。我假设这是因为当线程 2 获取锁时,线程 1 重新获取锁并再次打印。
  2. 当我在两个线程中的 down 和 up 函数调用之间使用 msleep(1000)mdelay(1000) 时,我会看到交替的打印。
  3. 当我在两个线程中再次调用 up 函数后使用 msleep(1000) 时,打印不会交替。
  4. 当我在两个线程中调用 up 函数后使用 mdelay(1000) 时,我会看到备用打印,但当我删除模块时,整个系统会卡住

有人可以帮助我理解上述观察结果吗?

最佳答案

单个信号量不会为您提供交错保证。您需要两个信号量来强制执行交错。例如

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);

并且您需要在卸载模块之前解锁信号量,以便让线程正常关闭。

关于c - 带有信号量卡住的 Linux 内核线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25805616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com