0

I am trying to avoid race conditions in my code, and I am currently working with a single hyperthreaded CPU, so there are two logical CPUs, each with their own thread. If my understanding of hyperthreading is correct, these threads share the same resources, but their actions are actually time-sliced, not concurrent. Is it still possible for race conditions to emerge between these two hyperthreads?

For example, is there reason for me to change this:

Connection& connection = connections[num_connections];
... do some stuff
++num_connections;

to this:

Connection& connection = connections[num_connections++];
... do some stuff
  • 2
    a) The distinction between hyperthreading and threading is hidden from by the threading environment. b) Neither code construct is thread-safe. You will need to so more research. – Bob Dalgleish Jun 29 '16 at 15:15
  • 1
    Time slicing is all that is required for races. There is no possible race that is not reproducible with time slicing on a unicore CPU. – usr Jun 29 '16 at 15:27
  • 1
    @usr Not to detract from the question itself, but is that entirely true on systems with a relaxed memory model? I would think that time-slicing a unicore can only emulate sequential consistency on a multi-core system. I don't see how it can emulate race conditions that can only be caused by memory-reordering. Going back to the question on hand, I don't know if Intel says anything about memory-reordering between hyperthreads on the same core. But clearly the programmer must assume the worst-case. – Mysticial Jun 29 '16 at 15:40
  • Hm... you're right! @Mysticial On the other hand the compiler can reorder just as much as the CPU can, right? I always thought the two were equal in capabilities. I think this was in the Herb Sutter talk "Atomic Weapons". Certainly in C++ it's true due to undefined behavior. – usr Jun 29 '16 at 15:42
  • @usr Yeah, compiler-stuff is a completely different thing. But you're right in that it all falls under the UB umbrella. – Mysticial Jun 29 '16 at 15:47

2 Answers2

1

It's possible.

If both threads execute a logic like

if(condition){
 donate1MillionDollars
 condition=false
}

even with time slicing, the two threads can enter the if block, and you become a lot poorer than expected :)

Without knowing what "do some stuff" implies, it's hard to answer specifically for your use case.

C4stor
  • 8,355
  • 6
  • 29
  • 47
1

Since you can't control the order of events between threads, or when a thread will be preempted, of course race conditions can cause failures.

Race condition-generated failures don't require simultaneous execution.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56