mutexs for synchronization between kernel threads?

Johannes Erdfelt (jerdfelt@sventech.com)
Wed, 21 Apr 1999 15:22:35 -0400


I've spent the better part of a day looking for information on mutexs in
the kernel. I'm a bit more confused now than when I started since the
kernel documentation isn't very clear (Is there a Kernel tutorial of
sorts?)

I would assume that I would use the semaphore support offered up by
asm/semaphore.h and the spinlock support offered up by asm/spinlock.h

I'm having some issues with it in my code, and I think what I'm doing is
correct and I have bugs elsewhere, but I wanted to make sure that it's
what I'm expecting.

I have the possibility of 2 kernel threads (created via kernel_thread)
and an interrupt handler to access the same data structure.

My code is similar to this:

#include <asm/spinlock.h>
#include <asm/semaphore.h>

static spinlock_t spinlock = SPIN_LOCK_UNLOCKED;
static struct semaphore lock = MUTEX;

void interrupt_handler(...)
{
unsigned long flags;

spin_lock_irqsave(&spinlock, flags);
/* Stuff on structure */
spin_unlock_irqrestore(&spinlock, flags);
}

#define lock_struct(flags) \
spin_lock_irqsave(&spinlock, flags); \
down(&lock);

#define unlock_struct(flags) \
up(&lock); \
spin_unlock_irq_restore(&spinlock, flags);

void kernel_thread_a(...)
{
unsigned long flags;

while (something) {
/* ... */
lock_struct(flags);
/* Stuff on structure */
unlock_struct(flags);
/* ... */
}
}

void kernel_thread_b(...)
{
unsigned long flags;

while (something) {
/* ... */
lock_struct(flags);
/* Stuff on structure */
unlock_struct(flags);
/* ... */
}
}

I use the spinlock to synchronize the IRQ access (UP and SMP). The
semaphore (mutex) is used to synchronize thread access. Thread B will
access the structure most often and A will only do anything to the
structure if something horrible goes wrong.

Does this look sane? Am I doing the right thing?

JE

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.rutgers.edu
Please read the FAQ at http://www.tux.org/lkml/