Incrementing is not an atomic operation. As such each thread is likely to corrupt the counter value if they access it simultaneously. If you wish for multiple threads to access a variable at once you must only use atomic operations or wrap the operations in a mutex or semaphore.
The simplest fix you could make, assuming you are using gcc would be to replace the line
counter++;
with
__sync_fetch_and_add(&counter, 1);
This will replace the increment with an atomic increment and hopefully the program will execute correctly.
You can find much more information about atomic operations here: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html