1

I have multiple threads that are accessing the same data and it is too painful to make them thread safe. Therefore, they are now forced to run only on one CPU core using CPU affinity and only one thread can be running at the same time.

I was wondering if it is possible to group these threads and let them float to other CPU cores all together ? In this way, I don't have to spare one CPU core for these threads.

This is based on Unix/BSD platform

ARH
  • 1,355
  • 3
  • 18
  • 32
  • 1
    You don't really have multiple threads since only one can be running at a time. Why not just do it the right way or else get rid of threads? – stark Jun 05 '15 at 19:35
  • Curious - is making them run on one CPU only because of system limitations, or because you are attempting to avoid locking slow downs? – Michael Dorgan Jun 05 '15 at 19:41
  • Also, you may want to post what you are doing that requires your solution. You may be surprised by an answer or two that could solve the root problem instead of the secondary issue you are working with now. – Michael Dorgan Jun 05 '15 at 19:42
  • @MichaelDorgan because I am trying to avoid locking. – ARH Jun 05 '15 at 19:47
  • @stark, I wish if I can do that. Looking for simpler solution though. – ARH Jun 05 '15 at 19:51

2 Answers2

2

There is no way to do this on Windows. I don't know about Unix/Linux but I doubt it's possible.

Note, that this does not make your system thread-safe. Even on uni-processor machines thread-safety is a concern.

i++

is not atomic. Two thread can both read i, then compute i+1, then write i. That results in a lost update.

You need to throw this approach away. Probably, you should be using a global lock that you hold around accesses to shared mutable state. That makes all these concerns go away and is reasonably simple to implement.

usr
  • 168,620
  • 35
  • 240
  • 369
  • that would be the case for uncontrolled context switch between threads. I do make sure that switch can only happen at specific line of my code not between i++ instructions. – ARH Jun 05 '15 at 19:54
  • How do you control context switches? That would require freezing all other threads which would make your scheduling solution unnecessary. – usr Jun 05 '15 at 19:55
  • 2
    @ARH It sounds like there's a lot you're not telling us about how your code works. – David Schwartz Jun 05 '15 at 20:17
  • @DavidSchwartz - yeah. There is something 'off' about OP's requirement and implementation, but not enough info to tell what it is:( – Martin James Jun 06 '15 at 07:55
1

Either make the code thread safe or use just one thread.

The simplest solution is probably the "one big lock" model. With this model, one lock protects all the data that's shared among the threads and not handled in a thread-safe way. The threads start out always holding the lock. Then you identify all the points where the threads can block and release the lock during that block.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278