Fernanda Brum Lousada
Fernanda Brum Lousada

Reputation: 371

Multithread behavior?

I've the following MFC console program:

UINT ThreadFunc(LPVOID);

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    for (int i = 0; i < 5; i++)
    {
        if (AfxBeginThread(ThreadFunc, (LPVOID)i))
        {
            printf("Thread launched: %d\n", i);
        }
    }

    Sleep(2000);

    system("pause");

    return 0;
}

UINT ThreadFunc(LPVOID n)
{
    for (int i = 0; i < 10; i++)
    {
        printf("%d%d%d%d%d%d%d%d\n", (int)n, (int)n, (int)n, (int)n, (int)n, (int)n, (int)n, (int)n);
    }

    return 0;
}

Whose output, in some execution, is:

Thread launched: 0
00000000
00000000
00000000
00000000
00000000
00000000
Thread launched: 1
11111111
11111111
11111111
Thread launched: 2
00000000
00000000
00000000
00000000
33333333
33333333
33333333
Thread launched: 3
11111111
11111111
11111111
11111111
44444444
44444444
44444444
Thread launched: 4
22222222
22222222
22222222
22222222
22222222
22222222
22222222
22222222
22222222
22222222
11111111
11111111
11111111
44444444
44444444
44444444
44444444
44444444
44444444
44444444
33333333
33333333
33333333
33333333
33333333
33333333
33333333

So I would like to understand what is going on here. Why do thread's prints differ from each other (one thread prints numbers that should be printed by other thread)? Why do one thread only prints (all at once!) after the next thread to be created?

Upvotes: 2

Views: 63

Answers (1)

shf301
shf301

Reputation: 31404

Each thread is printing the numbers that are assigned to it. It's just that all of your threads are running at the same time so their output is overlapping. You'll probably see what is happening better if you add printf at the start and end of the of ThreadFunc.

Windows make no guarantees on the order that threads will run or exactly how long a thread will run for, which is why you see variable. You will most likely get different results each time you run your program.

Upvotes: 2

Related Questions