samir82show

worker model reader-writer spin lock

Sep 25th, 2015
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. #include <linux/module.h>
  2. #include <linux/completion.h>
  3. #include <linux/kernel.h>
  4. #include <linux/init.h>
  5. #include <linux/string.h>
  6. #include <linux/kthread.h>
  7. #include <linux/mutex.h>
  8. #include <linux/wait.h>
  9. MODULE_LICENSE("GPL");
  10. MODULE_AUTHOR("Sanfoundry-Student");
  11. MODULE_DESCRIPTION("Kernel Producer-Consumer Thread assignment");
  12.  
  13. //struct completion
  14.  
  15. struct arg {
  16. char name[20];
  17. } arg[4] = {{"producer 1"}, {"consumer 1"}, {"producer 2"}, {"consumer 2"}};
  18.  
  19. static struct task_struct *threadtest1;
  20. static struct task_struct *threadtest2;
  21. static struct task_struct *threadtest3;
  22. static struct task_struct *threadtest4;
  23. int i;
  24. //DEFINE_SPINLOCK (workerLK);
  25. DEFINE_RWLOCK (workerLK);
  26. static int sanfd_producer (void *arg) {
  27. char *c = (char *)arg;
  28. while (!kthread_should_stop ()) {
  29. write_lock (&workerLK);
  30. /*critical section*/
  31. i++;
  32. printk (KERN_INFO "%s written, %d\n", c, i);
  33. /*critical section*/
  34. write_unlock (&workerLK);
  35. schedule ();
  36. }
  37. return 0;
  38. }
  39. static int sanfd_consumer (void *arg) {
  40. char *c = (char *)arg;
  41. while (!kthread_should_stop ()) {
  42. read_lock (&workerLK);
  43. /*critical section*/
  44. printk (KERN_INFO "%s read, %d\n", c, i);
  45. /*critical section*/
  46. read_unlock (&workerLK);
  47. schedule ();
  48. }
  49. return 0;
  50. }
  51.  
  52.  
  53. static int __init sanfd_kthread_init(void)
  54. {
  55. printk(KERN_INFO "Loaded kthreadwork module\n");
  56. printk (KERN_ERR "arg # 0 prod is %s\n", arg[2].name);
  57. printk (KERN_ERR "arg # 0 cons is %s\n", arg[3].name);
  58. threadtest1 = kthread_run (sanfd_producer, &arg[0], "%s%d\n", arg[0].name, i);
  59. threadtest2 = kthread_run (sanfd_consumer, &arg[1], "%s%d\n", arg[1].name, i);
  60. threadtest3 = kthread_run (sanfd_producer, &arg[2], "%s%d\n", arg[2].name, i);
  61. threadtest4 = kthread_run (sanfd_consumer, &arg[3], "%s%d\n", arg[3].name, i);
  62. if (!threadtest1 || !threadtest2 || !threadtest3 || !threadtest4) {
  63. printk (KERN_ERR "unable to start kernel thread\n");
  64. return 1;
  65. }
  66. printk (KERN_INFO "threads started\n");
  67. return 0; // Non-zero return means that the module couldn't be loaded.
  68. }
  69.  
  70. static void __exit sanfd_kthread_cleanup(void)
  71. {
  72. printk(KERN_INFO "Cleaning up kthreadwork module.\n");
  73. kthread_stop (threadtest1);
  74. kthread_stop (threadtest2);
  75. kthread_stop (threadtest3);
  76. kthread_stop (threadtest4);
  77. }
  78.  
  79. module_init(sanfd_kthread_init);
  80. module_exit(sanfd_kthread_cleanup);
Advertisement
Add Comment
Please, Sign In to add comment