What if we leave i off the by-value variables list?

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
void multi_dns_conc(
    
size_t N, char **names, struct addrinfo **infos )
{
    
size_t i, done = 0;
    
semaphore_t done_sem;
    
sem_init( &done_sem, 0 );
    
for( i = 0; i < N; ++i )
    
{
        
activate     
        
{
            
assert( 0 == getaddrinfo(
                
names[i], NULL, NULL, &infos[i] ) );
            
if( ( ++done ) == N )
                
sem_inc( &done_sem );
        
}
    
}
    
sem_dec( &done_sem );
}

This is a pretty nasty little bug, because the code will probably work most of the time. The potential problem is the following sequence:

  1. One of the lookup activities yields
  2. The "main" activity increments i
  3. The lookup activity resumes and now has the wrong value for i

This kind of bug deserves some more thinking. Maybe some automatic warnings could happen.