Linux 内核线程间同步

本文介绍了Linux内核中线程间的同步机制,包括信号量和互斥锁的使用方式,以及如何通过条件变量实现线程间的等待和唤醒。通过具体的代码示例展示了如何在内核线程中实现资源的保护和线程之间的协调。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用户空间的线程间同步机制最终需要内核提供相应的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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值