Linux 内核线程间同步

来源:互联网 发布:网络监控是什么意思 编辑:程序博客网 时间:2024/06/05 18:01

用户空间的线程间同步机制最终需要内核提供相应的wait, wake up, schedule机制。如果是内核线程间的同步就是直接对这些wait,wake up,schedule的应用。

 

信号量的使用:

struct semaphore sem1,sem2;

sema_init(&sem1, 0);

sema_init(&sem2, 0);

 

void thread1(void*)

{

           while(!kthread_should_stop())

{

                      down(&sem1);

                       /*process job*/

                       up(&sem2);

          }

}

 

void thread2(void*)

{

           while(!kthread_should_stop())

{

                      down(&sem2);

/*process job*/

up(&sem1);

          }

}

/*down / up 操作也是对wait, wake up, schedule的封装*/

 

互斥锁和“条件变量“的使用:

Struct task_struct *thread0,*thread1;

Struct mutex *mutex;

wait_queue_head_t wq;

int condition ;

 

void thread0_process(void*)

{

           set_current_state(TASK_INTERRUPTIBLE);

           while(!kthread_should_stop())

{

     mutex_lock(&mutex);

while (condition is false)  //这里用while而不是if

                 thread_suspend();

     /*processjob*/

     mutex_unlock(&mutex);

}

}

 

void thread1_process(void*)

{

           set_current_state(TASK_INTERRUPTIBLE);

           while(!kthread_should_stop())

{

     mutex_lock(&mutex);

if (condition is true)

                 thread_resume();

     mutex_unlock(&mutex);

}

}

 

thread_init ()

{

thread0 = kthread_create(thread0_process,NULL,”thread0”);

wake_up_process(thread0);

}

 

thread_exit()

{

           kthread_stop(thread0);

}

 

/* 相当于pthreadpthread_cond_wait*/

thread_suspend(void)

{

           init_waitqueue_head(&wq);

           mutex_unlock(&mutex);

           wait_event_interruptible(wq,0);

           mutex_lock(&mutex) ;

}

 

/* 相当于pthreadpthread_cond_signal*/

thread_resume(void)

{

          wake_up_interruptible(wq);

}

原创粉丝点击