Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <linux/module.h>
- #include <linux/semaphore.h>
- #include <linux/delay.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 arg {
- char name[20];
- } arg[4] = {{"prod1"}, {"cons1"}, {"prod2"}, {"cons2"}};
- static struct task_struct *threadtest0;
- static struct task_struct *threadtest1;
- static struct task_struct *threadtest2;
- static struct task_struct *threadtest3;
- int i;
- DECLARE_COMPLETION (compLK1);
- DECLARE_COMPLETION (compLK2);
- DEFINE_SPINLOCK (workLK);
- DEFINE_SEQLOCK(seqLK1);
- DEFINE_SEQLOCK(seqLK2);
- static DECLARE_MUTEX (sem);
- static int sanfd_producer (void *arg) {
- char *c = (char *)arg;
- while (!kthread_should_stop ()) {
- if ((strcmp (c, "prod1")) == 0) {
- write_seqlock (&seqLK1);
- i++;
- printk (KERN_INFO "%s written, %d\n", c, i);
- write_sequnlock (&seqLK1);
- schedule ();
- } else {
- write_seqlock (&seqLK2);
- i++;
- printk (KERN_INFO "%s written, %d\n", c, i);
- write_sequnlock (&seqLK2);
- schedule ();
- }
- }
- return 0;
- }
- static int sanfd_consumer (void *arg) {
- unsigned seq;
- char *c = (char *)arg;
- while (!kthread_should_stop ()) {
- if ((strcmp (c, "cons1")) == 0) {
- do {
- seq = read_seqbegin(&seqLK1);
- printk (KERN_INFO "%s read, %d\n", c, i);
- } while (read_seqretry(&seqLK1, seq));
- schedule ();
- } else {
- do {
- seq = read_seqbegin(&seqLK2);
- printk (KERN_INFO "%s read, %d\n", c, i);
- } while (read_seqretry(&seqLK2, seq));
- schedule ();
- }
- }
- return 0;
- }
- static int __init sanfd_kthread_init(void)
- {
- printk(KERN_INFO "Loaded kthreadwork module\n");
- threadtest0 = kthread_run (sanfd_producer, &arg[0], "%s%d\n", arg[0].name, i);
- threadtest1 = kthread_run (sanfd_consumer, &arg[1], "%s%d\n", arg[1].name, i);
- threadtest2 = kthread_run (sanfd_producer, &arg[2], "%s%d\n", arg[2].name, i);
- threadtest3 = kthread_run (sanfd_consumer, &arg[3], "%s%d\n", arg[3].name, i);
- if (!threadtest0 || !threadtest1 || !threadtest2 || !threadtest3) {
- 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 (threadtest0);
- kthread_stop (threadtest1);
- kthread_stop (threadtest2);
- kthread_stop (threadtest3);
- }
- module_init(sanfd_kthread_init);
- module_exit(sanfd_kthread_cleanup);
Advertisement
Add Comment
Please, Sign In to add comment