title: using semaphore in Perl
body: <p>this is a part of my code, which compiles some projects in parallel:</p>
  
  <pre><code>#main:#
  our $sem = Thread::Semaphore-&gt;new();
  
  for ($i = 0; $i &lt; $cores_num-1; $i++)
  {
      # Generating process
      local $curr_pid = fork ();
      # Child
      if ($curr_pid == 0)
      { 
          compiling_process($i,*REPORT);
          exit(0);
      }
      # Parent
      elsif (abs($curr_pid) &gt; 10)
      {
          sleep (1);
          $running_processes++;   
      }
      # Error
      else
      {
          print "Error while forking!! \n";
          exit (0);
      }
  }
  
  # parent process:
  compiling_process($i,*REPORT);
  # Wait:
  while ($running_processes &gt; 0)
  {
      $kid = 0;
      $kid = waitpid(-1,WNOHANG);
      if (abs($kid) &gt; 10)
      {
          $running_processes--;
      }
      sleep (1);
  }
  
  
  
  
  sub compiling_process{
  local $id = $_[0];
  *REPORT = $_[1];
  # Run until all targets are built:
  
  while (1)   
  {
  $sem-&gt;down();   
  ##critical section
  $sem-&gt;up();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>This code is for compiling in parallel.
  while running this code- sometimes I see 2 cores inside of the critical section at the same time! (the code works fine and all the projects are being built, but I must solve this problem..it causes a wast of time + wrong prints ) 
  I am kind of desperate because I don't know what am I doing wrong.
  is it wrong using semaphore in a function? ("sub compiling_proces")</p>
  
  <p>any help would be appreciated! 
  Thanks a lot.</p>