0

So I'm designing a new software interface for a USB HID device and I have a question about concurrency protection. I assume that I will have to add concurrency protection around my the calls to ReadFile and WriteFile (please correct me if wrong) as these may be called from different threads in my design.

In the past I have sometimes used static booleans to implement thread safety, adding a loop with a 1ms wait on it until the bool indicated that the code was safe to enter. I have also used CriticalSections. Could anyone tell me if CriticalSections are fundamentally better than using a static bool. I know that I wont have to code up a waiting loop, but what polling rate do they use in VC++ to check the state of the lock? Are they hooked into the OS in some way that makes them better? Is using a bool for a concurrency check not always safe? etc.

Ian
  • 4,169
  • 3
  • 37
  • 62
  • C++11 added thread support to the standard library, you should look at using something like std::mutex – Rastaban Apr 24 '14 at 04:10
  • Nah, mutex is too expensive. CriticalSections should do it. I'll look for them in the std lib. – Ian Apr 24 '14 at 15:43
  • I see that std::mutex is not necessarily a windows mutex, but can be implemented as a CS. – Ian Apr 24 '14 at 19:49

2 Answers2

1

I don't know much about C++, but concurrency usually isn't implemented by polling, and generally shouldn't be—polling wastes processor time and wastes energy. The two main low-level approaches are

  1. Blocking on a lock, perhaps with a timeout.

  2. Using a lock-free primitive, most likely either compare-and-set or compare-and-swap.

These approaches are both supported by typical modern hardware. They lead to very different "flavors" of interaction. Writing lock-free data structures is best left to the experts (they tend to be complicated, and, more importantly, it tends to be difficult to see whether they are correct and whether they guarantee progress in the face of contention—their descriptions are usually accompanied by pages of proofs). Fortunately, you can get libraries of them, and they are faster and better-behaved than blocking ones in many but not all cases.

dfeuer
  • 48,079
  • 5
  • 63
  • 167
  • No sure what lock-free structures or primitives are, but I'm not protecting data structures, just USB input/output. – Ian Apr 24 '14 at 15:54
0

Well never mind. I'll just stick with critical sections. I was hoping to get some interesting information about how critical sections work, or at least a reference to an article about that. IE - why they are different than just writing your own polling loop. I see from this discussion: std::mutex performance compared to win32 CRITICAL_SECTION that there is some confusion about how std::mutex works, but I'm thinking that it is better to use CRITICAL_SECTIONS as it seems to be the surest way to get the the fastest concurrency protection on Windows.

Thanks anyways.

Community
  • 1
  • 1
Ian
  • 4,169
  • 3
  • 37
  • 62