Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <linux/module.h>
- #include <linux/completion.h>
- #include <linux/kernel.h>
- #include <linux/init.h>
- #include <linux/string.h>
- #include <linux/kthread.h>
- #include <linux/mutex.h>
- #include <linux/wait.h>
- MODULE_LICENSE("GPL");
- MODULE_AUTHOR("Sanfoundry-Student");
- MODULE_DESCRIPTION("Kernel Producer-Consumer Thread assignment");
- //struct completion
- struct arg {
- char name[20];
- } arg[4] = {{"producer 1"}, {"consumer 1"}, {"producer 2"}, {"consumer 2"}};
- static struct task_struct *threadtest1;
- static struct task_struct *threadtest2;
- static struct task_struct *threadtest3;
- static struct task_struct *threadtest4;
- int i;
- //DEFINE_SPINLOCK (workerLK);
- DEFINE_RWLOCK (workerLK);
- static int sanfd_producer (void *arg) {
- char *c = (char *)arg;
- while (!kthread_should_stop ()) {
- write_lock (&workerLK);
- /*critical section*/
- i++;
- printk (KERN_INFO "%s written, %d\n", c, i);
- /*critical section*/
- write_unlock (&workerLK);
- schedule ();
- }
- return 0;
- }
- static int sanfd_consumer (void *arg) {
- char *c = (char *)arg;
- while (!kthread_should_stop ()) {
- read_lock (&workerLK);
- /*critical section*/
- printk (KERN_INFO "%s read, %d\n", c, i);
- /*critical section*/
- read_unlock (&workerLK);
- schedule ();
- }
- return 0;
- }
- static int __init sanfd_kthread_init(void)
- {
- printk(KERN_INFO "Loaded kthreadwork module\n");
- printk (KERN_ERR "arg # 0 prod is %s\n", arg[2].name);
- printk (KERN_ERR "arg # 0 cons is %s\n", arg[3].name);
- threadtest1 = kthread_run (sanfd_producer, &arg[0], "%s%d\n", arg[0].name, i);
- threadtest2 = kthread_run (sanfd_consumer, &arg[1], "%s%d\n", arg[1].name, i);
- threadtest3 = kthread_run (sanfd_producer, &arg[2], "%s%d\n", arg[2].name, i);
- threadtest4 = kthread_run (sanfd_consumer, &arg[3], "%s%d\n", arg[3].name, i);
- if (!threadtest1 || !threadtest2 || !threadtest3 || !threadtest4) {
- printk (KERN_ERR "unable to start kernel thread\n");
- return 1;
- }
- printk (KERN_INFO "threads started\n");
- return 0; // Non-zero return means that the module couldn't be loaded.
- }
- static void __exit sanfd_kthread_cleanup(void)
- {
- printk(KERN_INFO "Cleaning up kthreadwork module.\n");
- kthread_stop (threadtest1);
- kthread_stop (threadtest2);
- kthread_stop (threadtest3);
- kthread_stop (threadtest4);
- }
- module_init(sanfd_kthread_init);
- module_exit(sanfd_kthread_cleanup);
Advertisement
Add Comment
Please, Sign In to add comment