0

I'm working on solving the Producer/Consumer problem through different methods. The one I'm currently working on involves my own implementation of a semaphore, paired with Peterson's solution to protect the semaphore's down() and up() function calls.

The problem is, I'm working in C, and the only way I can think of creating a semaphore would be to use a struct with function pointers for down() and up(). Is this the right idea?

  • 1
    The function pointers seem unrelated to the problem: you can call `up(my_semaphore);` instead of `my_semaphore->up(my_semaphore);`. (In C you can't really have `my_semaphore->up()` without arguments, since there is no implicit `this` argument passed so that the function would know which semaphore called it.) – Arkku Feb 27 '14 at 05:08

2 Answers2

2

You will likely want to use some OS-provided or hardware-provided synchronization primitive. Examples include system calls (e.g. Linux's futex call, Windows' EnterCriticalSection), hardware swap calls (e.g. cmpxchg on x86, ldrex/strex on ARM), or library functions which use one of these methods (e.g. pthread_mutex).

Trying to do synchronization without any help from the OS or hardware is likely to be quite difficult.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

Check futex, it is a user space syn primitive. But I don't think you're looking for something this much complicated.

brokenfoot
  • 11,083
  • 10
  • 59
  • 80