Global variables and data races

Global variables and data races

Imagen de newport_j

Being somewhat new to data races and Cilk,I am confused as to how global variables are more susceptible than local variaables to a data race. Inan examplein the Programmer's Guide the data race problem was solved with changing a global variable to a local variable.

That is all you got to do?

Newport_j

publicaciones de 2 / 0 nuevos
Último envío
Para obtener más información sobre las optimizaciones del compilador, consulte el aviso sobre la optimización.
Imagen de William Leiserson (Intel)

Global variables are prime candidates for races. If you imagine some piece of memory to which many threads and/or workers have access, and if writes are happening, _that's_ where values are going to get clobbered.

More generally, we use the term "non-local" to refer to variables that are in danger of racing. "Non-local" variables includes global variables, but it also includes, e.g., variables to which a pointer is passed between threads and/or workers. The solution is often trivial: make the non-local variable local. This is not always an option, but it is a good first idea. If you can do that, and if creating the variable is cheap, that's the right answer. E.g., it is often a good idea to move an integer declaration inside a cilk_for loop when iterations of the loop do not depend on each other. You couldn't do that in C. You needed all variable declarations up front.* But in C++ you can declare variables wherever you like. Likewise in Cilk++.

You can't always simply move the declaration around, however. In many such cases, it is possible, then, to wrap the variable with a reducer. A reducer is not trivially cheap like, e.g., an integer, but they solve the race condition by providing different views of the variable. This is often a possibility with global variables -- make a global reducer.

Reducers are not always the answer, though. In the remaining cases, you have to be more clever. Sometimes you have to refactor code or, in extreme cases, use locks. We have been trying to devise an acceptable way to implement other kinds of hyperobjects, but at this time reducers are the only ones that are available.

---

* technically, in C, you could open a new block inside a function and start declaring variables there, but traditionally, you declare all variables at the beginning of the function.

Inicie sesión para dejar un comentario.