Home >Backend Development >C++ >Is foreach Loop Thread-Safe When Used with Closures?

Is foreach Loop Thread-Safe When Used with Closures?

DDD
DDDOriginal
2025-01-22 07:01:08269browse

Is foreach Loop Thread-Safe When Used with Closures?

foreachThread 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn