Advertisement
Guest User

Syncing CPU_COUNT threads

a guest
Aug 9th, 2013
462
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. #include <linux/module.h>
  2. #include <linux/kernel.h>
  3. #include <linux/init.h>
  4. #include <linux/kthread.h>
  5.  
  6. #define CPU_COUNT 8
  7.  
  8. atomic_t count;
  9.  
  10. static struct task_struct *thread_init(int (*fn)(void *data),
  11.         void *data, int cpu)
  12. {
  13.     struct task_struct *ts;
  14.  
  15.     ts = kthread_create(fn, data, "per_cpu_thread");
  16.     kthread_bind(ts, cpu);
  17.     if (!IS_ERR(ts)) {
  18.         wake_up_process(ts);
  19.     } else {
  20.         printk(KERN_ERR "Failed to bind thread to CPU %d\n", cpu);
  21.     }
  22.     return ts;
  23. }
  24.  
  25. static void thread_sync(void)
  26. {
  27.     atomic_inc(&count);
  28.     while (atomic_read(&count) != CPU_COUNT);
  29. }
  30.  
  31. static void do_common_stuff(void) {
  32.     int cpu = smp_processor_id();
  33.     unsigned long flags = 0;
  34.  
  35.     printk(KERN_INFO "Syncing %d...\n", cpu);
  36.     local_irq_save(flags);
  37.     thread_sync();
  38.     printk(KERN_INFO "Syncing done %d.\n", cpu);
  39.     local_irq_restore(flags);
  40. }
  41.  
  42. static int per_cpu_thread_fn(void *data) {
  43.     do_common_stuff();
  44.     return 0;
  45. }
  46.  
  47. static int main_thread_fn(void *data) {
  48.     int i;
  49.  
  50.     atomic_set(&count, 0);
  51.     for (i = 1; i < CPU_COUNT; ++i) {
  52.         printk("Create thread on %d\n", i);
  53.         thread_init(per_cpu_thread_fn, NULL, i);
  54.     }
  55.  
  56.     do_common_stuff();
  57.     return 0;
  58. }
  59.  
  60. static int __init sync_init(void)
  61. {
  62.     thread_init(main_thread_fn, NULL, 0);
  63.     return 0;
  64. }
  65.  
  66. static void __exit sync_exit(void)
  67. {
  68. }
  69.  
  70. module_init(sync_init);
  71. module_exit(sync_exit);
  72.  
  73. MODULE_LICENSE("GPL");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement