c++ Threads inside for loop print wrong values

后端 未结 3 855
北恋
北恋 2021-02-18 18:55

I\'m trying to understand Multi-threading in c++, but I\'am stuck in this problem: if I launch threads in a for loop they print wrong values. This is the code:

#         


        
3条回答
  •  执笔经年
    2021-02-18 19:21

    Another thing :
    Do not wait until to have always an ordered sequence: 0, 1, 2, 3, ... because the multithreading execution mode has a specificity: indeterminism.

    Indeterminism means that the execution of the same program, under the same conditions, gives a different result.

    This is due to the fact that the OS schedules threads differently from one execution to another depending on several parameters: CPU load, priority of other processes, possible system interruptions, ...

    Your example contains only 5 threads, so it's simple, try to increase the number of threads, and for example put a sleep in the processing function, you will see that the result can be different from one execution to another .

提交回复
热议问题