C++ Thread, shared data

前端 未结 10 1845
悲&欢浪女
悲&欢浪女 2020-12-04 22:35

I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change? I don\'t

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 23:03

    As others have said the volatile keyword is your friend. :-)

    You'll most likely find that your code would work when you had all of the optimisation options disabled in gcc. In this case (I believe) it treats everything as volatile and as a result the variable is accessed in memory for every operation.

    With any sort of optimisation turned on the compiler will attempt to use a local copy held in a register. Depending on your functions this may mean that you only see the change in variable intermittently or, at worst, never.

    Using the keyword volatile indicates to the compiler that the contents of this variable can change at any time and that it should not use a locally cached copy.

    With all of that said you may find better results (as alluded to by Jeff) through the use of a semaphore or condition variable.

    This is a reasonable introduction to the subject.

提交回复
热议问题