Home >Backend Development >C++ >Is foreach Loop Thread-Safe When Used with Closures?
foreach
Thread safety of loops and closures
Ensuring thread safety requires careful consideration when using foreach
loops and closures. In the scenario you describe, there are two code snippets that differ in how they handle references to Foo objects in closures.
The first fragment passes the reference directly:
<code class="language-c#">foreach (Foo f in ListOfFoo) { Thread thread = new Thread(() => f.DoSomething()); threads.Add(thread); thread.Start(); }</code>
This approach is unsafe because the same f
reference is shared by all threads. This means that different threads may access and modify the same Foo object, leading to unpredictable behavior.
To ensure thread safety, you should create a copy of the reference inside the loop, as shown in the second snippet:
<code class="language-c#">foreach (Foo f in ListOfFoo) { Foo f2 = f; Thread thread = new Thread(() => f2.DoSomething()); threads.Add(thread); thread.Start(); }</code>
By creating a new f2
variable inside the loop, each thread has its own copy of the reference to the Foo object. This ensures that each thread is operating on a unique object, preventing race conditions and potential data corruption.
Note: This issue is not unique to threading. The same problem arises when using closures in asynchronous operations or event handlers, and special care is required to avoid unexpected behavior and maintain data integrity.
The above is the detailed content of Is foreach Loop Thread-Safe When Used with Closures?. For more information, please follow other related articles on the PHP Chinese website!