Race condition: Min and Max range of an integer

前端 未结 4 865
南旧
南旧 2020-12-30 20:44

I was recently asked this question in an interview.

Given the following code, what will be the min and max possible value of the static integer num?

4条回答
  •  时光说笑
    2020-12-30 20:52

    Your threads are updating a variable which is is not volatile that means it does not guarantee that every thread will see the updated value of num. Let consider the below execution flow of threads:

    Thread 1: 0->1->2 (2 iteration left)
    Thread 2: 0->1->2->3 (1 iteration left)
    Thread 3: 0->1->2->3 (1 iteration left)
    Thread 4: 0->1->2->3 (1 iteration left)
    Thread 5: 0->1->2->3 (1 iteration left)
    

    At this point, Thread 1 flushes the value 2 of num to memory and Thread 2,3,4,5 decide to read the num from the memory again (for any reason). Now:

    Thread 1: 2->3->4 (completed 2 iteration)
    Thread 2: 2->3 (completed 1 iteration)
    Thread 3: 2->3 (completed 1 iteration)
    Thread 4: 2->3 (completed 1 iteration)
    Thread 5: 2->3 (completed 1 iteration)
    

    Thread 1 flushes the value 4 to the memory and after that Theard 2,3,4.. flushes the value to the memory show the current value of the number will be 3 instead of 5

提交回复
热议问题