-1

The title may have been a little vague... I am working on a piece of software that is designed to perform one task. I would like this task to work in parallel, allowing for multiple asynchronous threads to perform the same task.

I am not concerned about the order of which these tasks get completed but I am concerned about the number of tasks that are running in parallel (CPU usage). I've had minimal experience with future's or the concept of semaphores in general...

I've done some reading and have found mixed opinions about similar scenarios. So I was hoping someone could point me to a good read or example for my use case.

  • 2
    This is really unclear. You're almost certainly worrying about something you shouldn't worry about until it becomes a problem, if it ever does. Unless, of course, you have good reason to worry. – Robert Harvey Jul 27 '16 at 14:55
0

You question is very broad. It'll take too long to explain you everything, but here some guidance.

You are looking for ways to do multithreading. In C++ you have several ways to launch parallel operations via the standard library:

  • thread that you can manage on your own,
  • and future, which are in fact objects that collect results from:
    • async, an asynchronous function call (often implemented internally via a thread pool)
    • packaged_task

In addition, you can launch parallel operations by using OpenMP if your compiler supports it (mainstream compilers do).

But as soon as you have several threads, you have to manage the synchronization between them, to ensure the processing remains "safe" (e.g. that one thread is not making a mess of a datastructure that is currently updated by another thread and therefore temporarily in an unstable state). Again C++ offers plenty of choices:

  • atomic variables that can be accessed from several threads without fear of data races
  • condition_variable which allow for a notification mechanism
  • mutex with their lock

You certainly can find some online tutorials on these topics. But I'd recommend you warmly Antony William's excellent book "C++ Concurrency in action: practical multithreading". It provides a step by step introduction to multithreading and its challenges, presents different techniques that you can use (such as locking with mutexes and lock_guard, or lock-free data structures) with plenty of well explained examples.

| improve this answer | |
-2

Your question makes clear that you want to implement Multithreading. I hope you have an understanding of it first. If not look this website, it explains clearly, https://www.tutorialcup.com/cplusplus/multithreading.htm#Thread-ID

There are many functions as you start to study in depth. Like:

  1. Mutex
  2. Thread_id
  3. Functions involving time and much more

And also have a look at Thread pool, and What is a thread pool?

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.