首页 > 解决方案 > 为什么 mutex_unlock 可以在没有被所有者调用的情况下工作

问题描述

互斥体必须稍后由获得它的同一任务释放。

上面的行出现在 kernel/locking/mutex.c 中 mutex_lock 的定义中。

我无法使用示例代码看到相同的行为。我有什么错误吗。请检查我下面的代码和 dmesg。

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/kthread.h>

MODULE_LICENSE("GPL");
DEFINE_MUTEX(my_lock);
struct task_struct *mythread;

static int threadfn(void *data)
{
    pr_info("Kernel thread running on processor:%d\n", smp_processor_id());
    pr_info("Kernel thread unlocking without calling lock on processor:%d\n", smp_processor_id());
    mutex_unlock(&my_lock);
    pr_info("Kernel thread unlocked without calling lock on processor:%d\n", smp_processor_id());
    return 0;
}

static int __init test_hello_init(void)
{
    mutex_init(&my_lock);
    pr_info("Init function running on processor:%d\n", smp_processor_id());
    mutex_lock(&my_lock);
    pr_info("Init function locked on processor:%d\n", smp_processor_id());
    mythread = kthread_run(threadfn, NULL, "mythread");
    msleep(8000);
    pr_info("Init function completed on processor:%d\n", smp_processor_id());
    return -1;
}

static void __exit test_hello_exit(void)
{
}

module_init(test_hello_init);
module_exit(test_hello_exit);

dmesg:

[27389.146151] Init function running on processor:5
[27389.146152] Init function locked on processor:5
[27389.146351] Kernel thread running on processor:2
[27389.146352] Kernel thread unlocking without calling lock on processor:2
[27389.146352] Kernel thread unlocked without calling lock on processor:2
[27397.385479] Init function completed on processor:5
insmod: ERROR: could not insert module ./hello.ko: Operation not permitted

标签: cconcurrencylinux-kernellinux-device-drivermutex

解决方案


推荐阅读