title: Linux Kernel Threads with spinlock freeze
body: <p>I have two kernel threads and I am trying to print from these two threads in alternate fashion. I am using <strong>spinlock</strong> to sync these two threads.</p>
  
  <pre><code> int kthread_1_function(void *data)
   {
       while(1)
       {
           spin_lock(&amp;lock1);
           pr_alert("In Kernel Thread 1!!!\n");
           spin_unlock(&amp;lock2);
  
          if(kthread_should_stop())
          {
              spin_unlock(&amp;lock2);
              return 1;
          }
       }
  
       return 0;
   }
  
   int kthread_2_function(void *data)
   {
       while(1)
       {
           spin_lock(&amp;lock2);
           pr_alert("In Kernel Thread 2!!!\n");
           spin_unlock(&amp;lock1);
  
          if(kthread_should_stop())
          {
              spin_unlock(&amp;lock1);
              return 2;
          }
        }
  
       return 0;
   }
  </code></pre>
  
  <p>In init module, I create these kernel threads (kthread_run) and cleanup_module stop these threads (kthread_stop).</p>
  
  <p>When I try to remove the module entire system hangs. By browsing the kernel source I could see that spin_lock disables preemption and kthread_stop tries to wake up the thread which is supposed to be killed and waits for the thread to exit and return. Not sure what is making my system hang. Logically speaking it should have worked fine.</p>
  
  <p>Note: When I initialize the spinlocks, I set lock1 as UNLOCKED and lock2 as LOCKED.</p>