C******e 发帖数: 1850 | 1 I have a mutlithread question need your help. I want to create a thread to
do some task in the background, but the problem is both this background
thread and the main() function will use a common global variable, say gdata.
For example, the background thread changes the value of gdata, and the main
() function uses gdata for some calculation. So how do I make sure the main(
) function uses the up-to-date value of gdata? In other words, how do I
synchronize the value of gdata between the backgrou | r*********r 发帖数: 3195 | | C******e 发帖数: 1850 | 3 could you be more specific please? this is something new to me. | m*****e 发帖数: 4193 | 4
Then you won't get the answer from BBS.
Read some books on multithreading programing first.
【在 C******e 的大作中提到】 : could you be more specific please? this is something new to me.
| a****l 发帖数: 8211 | 5 it seems you only have two threads, one main, one background. Then it's very
simple, no need for "advanced" things like mutex. Just add one global
boolean, when background has a new value and boolean is 0, write the value,
set boolean to 1; the main thread keeps checking boolean, if 1, read value,
finish work, then set boolean to 0.
gdata.
main
main(
)
【在 C******e 的大作中提到】 : I have a mutlithread question need your help. I want to create a thread to : do some task in the background, but the problem is both this background : thread and the main() function will use a common global variable, say gdata. : For example, the background thread changes the value of gdata, and the main : () function uses gdata for some calculation. So how do I make sure the main( : ) function uses the up-to-date value of gdata? In other words, how do I : synchronize the value of gdata between the backgrou
| p***o 发帖数: 1252 | 6 You need to declare the global boolean to be 'volatile' for this to work
with modern compilers on most modern multicore processors. Roughly speaking,
you need to tell the compiler and the processor NOT to reorder the writes
in the background and the read/write in the main thread. Search for the
keyword 'memory barrier', and that's why it's better for him to learn
from some decent books ...
very
,
,
【在 a****l 的大作中提到】 : it seems you only have two threads, one main, one background. Then it's very : simple, no need for "advanced" things like mutex. Just add one global : boolean, when background has a new value and boolean is 0, write the value, : set boolean to 1; the main thread keeps checking boolean, if 1, read value, : finish work, then set boolean to 0. : : gdata. : main : main( : )
|
|