我在我的可加载模块中创建了2个Linux内核线程,并将它们绑定到在双核Android设备上运行的独立CPU内核。运行这几次后,我注意到设备重新启动,并且硬件看门狗定时器复位。我始终如一地解决问题。什么可能导致僵局?这段代码为什么会死锁?
基本上,我需要做的是确保两个线程同时在不同的内核上运行do_something(),而不会有人盗取cpu周期(即中断被禁用)。我正在使用一个自旋锁和一个易变的变量。我也有一个父线程在子线程上等待的信号量。
#define CPU_COUNT 2
/* Globals */
spinlock_t lock;
struct semaphore sem;
volatile unsigned long count;
/* Thread util function for binding the thread to CPU*/
struct task_struct* thread_init(kthread_fn fn, void* data, int cpu)
{
struct task_struct *ts;
ts=kthread_create(fn, data, "per_cpu_thread");
kthread_bind(ts, cpu);
if (!IS_ERR(ts)) {
wake_up_process(ts);
}
else {
ERR("Failed to bind thread to CPU %d\n", cpu);
}
return ts;
}
/* Sync both threads */
void thread_sync()
{
spin_lock(&lock);
++count;
spin_unlock(&lock);
while (count != CPU_COUNT);
}
void do_something()
{
}
/* Child thread */
int per_cpu_thread_fn(void* data)
{
int i = 0;
unsigned long flags = 0;
int cpu = smp_processor_id();
DBG("per_cpu_thread entering (cpu:%d)...\n", cpu);
/* Disable local interrupts */
local_irq_save(flags);
/* sync threads */
thread_sync();
/* Do something */
do_something();
/* Enable interrupts */
local_irq_restore(flags);
/* Notify parent about exit */
up(&sem);
DBG("per_cpu_thread exiting (cpu:%d)...\n", cpu);
return value;
}
/* Main thread */
int main_thread()
{
int cpuB;
int cpu = smp_processor_id();
unsigned long flags = 0;
DBG("main thread running (cpu:%d)...\n", cpu);
/* Init globals*/
sema_init(&sem, 0);
spin_lock_init(&lock);
count = 0;
/* Launch child thread and bind to the other CPU core */
if (cpu == 0) cpuB = 1; else cpuB = 0;
thread_init(per_cpu_thread_fn, NULL, cpuB);
/* Disable local interrupts */
local_irq_save(flags);
/* thread sync */
thread_sync();
/* Do something here */
do_something();
/* Enable interrupts */
local_irq_restore(flags);
/* Wait for child to join */
DBG("main thread waiting for all child threads to finish ...\n");
down_interruptible(&sem);
}
感谢Rasen:删除引用
最后的代码可以在这里找到。我修正了中断呼叫,但仍然看到问题。我不能在spin_lock()内移动(count!= CPU_COUNT),因为它会立即死锁。你有其他建议吗?我的要求是两个线程都应该在同一时间开始执行do_something()。 – Gupta
您必须保护读取'count'锁。我编辑了我的帖子以显示如何执行此操作。 –
再次感谢指针。这还没有解决我的问题。我看到其中一个线程正在旋转,而另一个线程永远不会增加计数器。您是否看到线程创建方式的问题? – Gupta