1. Do not use this code, delete them
It seems that after the end of the thread the task will be set to null, and calling kthread_stop () will result in a null pointer error
2. Do not pass a local variable into streams, use a global variable instead.
3. If you want the two threads to switch between themselves, use the wait_event and wake_up functions. Here is my code that works.
#include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/kthread.h> #include <linux/wait.h> MODULE_LICENSE("GPL"); int pid1 = 1; int pid2 = 2; DECLARE_WAIT_QUEUE_HEAD(wq); int condition; struct task_struct *task1; struct task_struct *task2; static int thread_function(void *data){ int *thread_id = (int*)data; int i = 0; while(i < 10){ printk(KERN_INFO "install kernel thread: %d\n", *thread_id); i++; if(*thread_id == 1) { wait_event(wq, condition == 0xA); condition = 0xB; wake_up(&wq); } else{ wait_event(wq, condition == 0xB); condition = 0xA; wake_up(&wq); } } return 0; } static int kernel_init(void) { condition = 0xA; task1 = kthread_create(&thread_function, (void *)&pid1, "pradeep"); task2 = kthread_create(&thread_function, (void *)&pid2, "pradeep"); //printk(KERN_INFO "After create kernel thread\n"); wake_up_process(task1); wake_up_process(task2); return 0; } int init_module(void) { kernel_init(); return 0; } void cleanup_module(void) { return; }
source share