title: about synchronization with using multiple semaphores
body: <p>hi there i'm working on an assignment about using POSIX threads with multi semaphores. the brief explanation of assignment is: there are 4 various data packets (char/video/audio/image), each of them carried by a different thread and also we have a shared buffer. maximum threads can work on system will be maintained by the user as an input. for example; if user enters 10 then maximum 10 thread could be created to transmit data packets over a buffer in a given time. now the confusing part for me is, this buffer can contains limited packets instantly. (for example it can contain maximum 10 char packets and 20 video packets etc.) so we have to have different semaphores for each data type. the issue i know how to control the buffer size with semaphore which is very simple, but cant set the correct idea of using semaphores of packets'. even i tried some different methods i always faced with deadlock errors. here is my pseudocode to understand more clearly of my program.</p>
  
  <pre><code>define struct packege
  define semaphore list
  
  main
  
  initialize variables and semaphores
  
  while threadCounter is less than MaxThreadNumber
  
  switch(random)
  case 0: create a character package
      create a thread to insert the package in buffer
  case 1: create a video package
      create a thread to insert the package in buffer
  case 2: create an image package
      create a thread to insert the package in buffer
  case 3: create an audio package
      create a thread to insert the package in buffer
  
  increment  threadCounter by one
  end of while
  
  create only one thread which will make the dequeue operation
  end of main
  
  producer function
  
  for i-&gt;0 to size_of_package
      sem_wait(empty_buffer) // decrement empty_buffer semaphore by size of package
  
      lock_mutex
          insert item into queueu
          decrement counter of the buffer by size of package
      unlock_mutex
  
  for i-&gt;0 to size_of_package
      sem_post(full_buffer) // increment full_buffer semaphore by size of package
  
  end of producer function
  
  consumer function
  
  while TRUE // Loops forever
  
      lock_mutex
  
          if queue is not empty
              dequeue
  
          increment counter of the buffer size of package
  
      unlock_mutex
  
  for i-&gt;0 to size_of_package // The reason why i making the sem_wait operation here is i cant make the dequeue in outer region of mutex.
      sem_wait(full_buffer)
  for i-&gt;0 to size_of_package
      sem_post(empty_buffer)
  end of consumer function
  </code></pre>
  
  <p>with this implementation programe works correctly. but i couldnt use semaphores properly which belongs to threads of packages. i can listen every recommandation and will be appreciated for every answer.</p>