문제

Is the += operator in c++ thread-safe?

It is possible to imagine a situation where it is not (Pseudocode):

int a = 5;

void thread1 () {
   a += 5;
}

void thread2 () {
   a += 5;
}

void main () {
    start_thread1 ();
    start_thread2 ();
    //Prints 15 always, but i think 10 is not impossible.
    printf ("%d\n", a);
}

It is obvious, that i must use Mutexes when += is overloaded, but do i have to set a mutex when working with simple types?

도움이 되었습니까?

해결책 2

It is not thread-safe.

To get synchronized behaviour without using blocking (mutexes) you could e.g. use the C++11 wrapper std::atomic.

std::atomic<int> a{5};

void work() {
    a += 5; // Performed atomically.
}

int main() {
    std::thread t1{work};
    std::thread t2{work};

    t1.join();
    t2.join();

    std::cout << a << std::endl; // Will always output 15.
}

다른 팁

+= is not atomic, so indeed it is not thread-safe and you could get 10. Or, frankly, cows being ejected from the moon. Perhaps a pizza materialising around your dog's nose.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top