inconsistent variable values in C# multithreading -
this question has answer here:
- captured variable in loop in c# 6 answers
i trying learn how use multithreading in c#. working this tutorial, explains using lambda expressions pass arguments. built toy program test this, confused output.
here code:
using system; using system.threading; namespace multithreadingapplication { class threadcreationprogram { public static void calltochildthread(int id) { console.writeline(string.format("child thread {0} starts", id)); } static void main(string[] args) { (int i=0; i<10; i++) { console.writeline(string.format("i: {0}", i)); thread childthread = new thread( () => calltochildthread (i) ); childthread.start(); } } } }
and here output:
i: 0 i: 1 child thread 1 starts i: 2 child thread 2 starts i: 3 child thread 3 starts i: 4 child thread 4 starts child thread 5 starts i: 5 i: 6 child thread 6 starts i: 7 i: 8 child thread 7 starts i: 9 child thread 9 starts child thread 8 starts child thread 10 starts
the child function prints out value of id passed. expected these range 0 9, calltochildthread
instead showing 1 10. can please explain why?
i ran program , got following result:
i: 0 i: 1 i: 2 child thread 2 starts i: 3 child thread 2 starts child thread 3 starts i: 4 child thread 4 starts child thread 4 starts i: 5 i: 6 i: 7 child thread 7 starts child thread 7 starts i: 8 i: 9 child thread 9 starts child thread 9 starts child thread 10 starts
this nicely demonstrates 1 of problems of multi-threading: shared variables. in line:
thread childthread = new thread( () => calltochildthread (i) );
you assume create lambda current value of i
. don't. create lambda reference i
, loop variable. when child thread reaches beginning of calltochildthread
(which might happen @ later time), value of i
evaluated , copied local variable id
.
the fix easy:
int _i = i; thread childthread = new thread(() => calltochildthread(_i));
this yield child threads 0 9.
Comments
Post a Comment