简体   繁体   中英

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. In init module, I create these kernel threads ( kthread_run ) and cleanup_module stop these threads ( 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. When I use msleep(1000) or mdelay(1000) between down and up function calls in both threads I see alternate prints.
  3. When I use msleep(1000) after up function call in both threads again the prints are not alternate.
  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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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