Ariel
Ariel

Reputation: 13

What makes Printf prints twice?

I did everything in my hands and think it's time to ask for help.

The following snippet of code runs by the main thread Only and my whole code doesn't call fork() at all.

inside another function:

pthread_mutex_lock(&(q->m));
...
else if (q->schedule_algorithm == RandomDrop)
        {
            int to_drop = 2;
            fprintf(stderr, "Before queue size: %d  \n", q->queue_size);
            fprintf(stderr, "To drop: %d  \n", to_drop);
            while (to_drop > 0)
            {
                // print process id to make sure it's same process
                fprintf(stderr, "process id: %d  \n", getpid());

                // print pthread id to make sure it's same thread
                fprintf(stderr, "\n");
                fprintPt(stderr,pthread_self());
                fprintf(stderr, "\n");
                
                int i = 0;
                int index = my_rand(q->queue_size);
                fprintf(stderr, "rand() chose: %d  \n", index);
                fprintf(stderr, "i: %d  \n", index);
                fprintf(stderr, "____________________\n");
                int removed_fd = find_key(q, index);
                requeue_not_thread_safe(q, removed_fd);
                Close(removed_fd);
                --to_drop;
                ++i;
            }
            fprintf(stderr, "After queue size: %d  \n", q->queue_size);
        }
...
pthread_mutex_unlock(&(q->m));

For some really strange reason, sometimes I see the same i value being printed twice. For example, one output was:

Before queue size: 5  
To drop: 2  
process id: 75300  

0x000e3f0a01000000
rand() chose: 2  
i: 2  
____________________
process id: 75300  

0x000e3f0a01000000
rand() chose: 2  
i: 2  
____________________
After queue size: 3  

How is this even possible?

Important Note: those are the only printings in my code so that second i can't come from different code...

Upvotes: 1

Views: 367

Answers (1)

catnip
catnip

Reputation: 25388

I don't see any great mystery here. You have:

to_drop = 2; (effectively)
while (to_drop > 0)
{
    ...
    --to_drop;
    ++i;
}

So the loop executes twice and therefore prints everything twice.

What is probably confusing you is that you have written:

fprintf(stderr, "i: %d  \n", index);

when you probably meant:

fprintf(stderr, "i: %d  \n", i);

Upvotes: 4

Related Questions