Using semaphore in C
I presume that you expected the result to be 20. Unfortunately this code may produce anything from 2 to 20.

Here is a scenario how 2 can be produced:

thread 1 grabs the semaphore (its tmp becomes 1)
thread 1 posts the semaphore in the mid-loop

thread 2 grabs the semaphore (sum is still 0)
thread 2 runs the loop for 9 times (sum becomes 9)
thread 2 posts the semaphore at the loop end

thread 1 takes over and completes its first loop
sum becomes 1
thread 1 posts the semaphore at the loop end

thread 2 takes over; its tmp becomes 2
thread 2 posts the semaphore in the mid-loop

thread 1 takes over and runs to completion

thread 2 (its tmp still 2) completes the second half of the loop
sum becomes 2


In your code the threads sleep while holding the semaphore (so sleeping is pretty much irrelevant). Contexts may only switch in the tiny window between sem_post and sem_wait. Most likely it never happens (scheduler doesn't have to switch threads), which explains why you are getting 20. Try to increase the window, say

    sem_post();
    sleep();
    sem_wait();


and see what happens.