Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi tasking with C++. Threads or different design?

Tags:

c++

I've always used scripting languages such as PHP where a page runs, completes running and gives an output. However, I want to do something a little different on C++ where I need to multi thread two tasks.

Firstly, the main thread should run, (let's say) a cpu temperature meter which refresh every 1 second, and the second thread should do something else. (like reading all directories under windows directory.)

With that said;

  1. Is using threads are my only chance or can I use a different programming concept for this task?

  2. Especially in gaming, there are loads of things running on the background. For example, AI for NPC's/Monsters, graphic engine, physics engine, player movement, keyboard interaction etc. They work in a single process, so how is it being handled?

like image 878
Aristona Avatar asked Jan 20 '26 20:01

Aristona


2 Answers

Create a thread for just reading cpu temperature meter and read directory for each second is over kill. No much gain from multi-threads but may have some pain of managing threads. You could put your TASK in a list and schedule them in second manner.

I am not sure about gaming stuff, but I believe they categorize the items/tasks and schedule/check/process in the loop. Some mount of threads are created for some dedicated tasks like socket communication, gui rendering etc, but create a dedicated thread for each item say a creep is over kill.

My suggestion is not to introduce multi-threads so easily into your application if you can do it in one thread. multi-threads will create other side affects like synchronization issue, thread management issue etc.

like image 100
billz Avatar answered Jan 22 '26 08:01

billz


Your challenge presumes task-based concurrency, I think. So, think about it in terms of asynchronous work, not just underlying threads. Howewer, many libraries provides safe, efficient and reliable high-level async API for concurrent tasks. I suggest following:

  1. Qt with QtConcurrent framework.
  2. POCO C++ library with Multithreading subpart.
  3. std::async template from C++11. Or boost::thread for old environments.

I should mention that standard std::async or boost replacement have different issues with task-based concurrency (it doesn't provide many of features to tweak execution policies, e.g. when fork new threads, when steal tasks, etc.)

like image 41
Eugene Mamin Avatar answered Jan 22 '26 08:01

Eugene Mamin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!