Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the "things to know" when diving into multi-threaded programming in C++

I'm currently working on a wireless networking application in C++ and it's coming to a point where I'm going to want to multi-thread pieces of software under one process, rather than have them all in separate processes. Theoretically, I understand multi-threading, but I've yet to dive in practically.

What should every programmer know when writing multi-threaded code in C++?

like image 631
Mark Avatar asked Jan 22 '10 15:01

Mark


People also ask

What is multithreaded programming in C?

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. C does not contain any built-in support for multithreaded applications.

Is multithreading hard to learn?

Multithreading isn't hard. Properly using synchronization primitives, though, is really, really, hard. You probably aren't qualified to use even a single lock properly. Locks and other synchronization primitives are systems level constructs.


2 Answers

I would focus on design the thing as much as partitioned as possible so you have the minimal amount of shared things across threads. If you make sure you don't have statics and other resources shared among threads (other than those that you would be sharing if you designed this with processes instead of threads) you would be fine.

Therefore, while yes, you have to have in mind concepts like locks, semaphores, etc, the best way to tackle this is to try to avoid them.

like image 138
Ariel Avatar answered Oct 06 '22 01:10

Ariel


I am no expert at all in this subject. Just some rule of thumb:

  1. Design for simplicity, bugs really are hard to find in concurrent code even in the simplest examples.
  2. C++ offers you a very elegant paradigm to manage resources(mutex, semaphore,...): RAII. I observed that it is much easier to work with boost::thread than to work with POSIX threads.
  3. Build your code as thread-safe. If you don't do so, your program could behave strangely
like image 35
Khaled Alshaya Avatar answered Oct 06 '22 01:10

Khaled Alshaya