Simple example of threading in C
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Explanation
- Thread Function: The
threadFunctionis a simple routine that outputs a message five times. This represents the task executed by the thread. - Thread Creation and Execution: We create a thread
thby passing thethreadFunctionto thestd::threadconstructor. This line initializes and begins execution of the thread. - Joining Threads: The
th.join()call is crucial. It ensures that the main thread waits forthto complete before exiting. If this step is ignored, the main function may terminate whilethis still running, potentially leading to application termination before the thread completes execution.
Key Considerations
- Thread Safety: When multiple threads access shared data, ensure thread safety by using synchronization mechanisms like mutexes (
std::mutex) and condition variables (std::condition_variable). These are required to avoid data races and undefined behavior. - Performance: Creating and executing threads has an overhead. Threads should be used judiciously, considering the trade-off between the performance overhead versus improved concurrency.
- Join vs. Detach: Threads can be detached using
th.detach(), allowing them to run independently from the main thread. However, this can lead to undefined behavior if the program ends before the detached thread completes.
Example with Mutex
Consider an advanced example illustrating mutex usage to safely update shared data:
Detailed Explanation
- Mutex: The
std::mutex mtx;declaration provides a mutual exclusion lock. Threads can lock the mutex, ensuring that only one thread accessessharedResourceat a time. - Lock Guard:
std::lock_guard<std::mutex> lock(mtx);is used to handle the locking automatically. It ensures the mutex is acquired at the lock guard's creation and released when it goes out of scope. - Protecting Shared Data: Each increment operation on
sharedResourceis enclosed within a lock guard, ensuring the resource is safely modified by only one thread at a time.
Summary Table
| Concept | Description |
| Thread Creation | Instantiate std::thread with a function to execute. |
| Joining Threads | Use join() to synchronize threads with the main thread. |
| Detaching | detach() allows independent thread execution. |
| Thread Safety | Use mutexes to protect shared data. |
| Lock Guard | Automatically manages mutex locking and unlocking. |
Conclusion
This article presented a fundamental look into threading in C++. Utilizing threads can greatly enhance the efficiency and responsiveness of software. However, care must be taken to manage resources appropriately and ensure thread safety. By adhering to best practices and utilizing C++11's std::thread and synchronization tools, developers can harness the power of concurrency effectively.
Understanding these basic principles is essential as developers delve into more complex multithreading scenarios. Each principle forms a building block towards developing reliable, high-performance, multithreaded applications.
Related reading
- Simplest and understandable example of volatile keyword in Java
- Simplest async/await example possible in Python
- Simplest async/await example possible in Python
- Simplest way to do a fire and forget method in C?
- Single Value Decomposition implementation C
- Sorting a point array efficiently in C?
- Simplest way to do a fire and forget method in c 4.0
- Single thread concept of JavaScript running in browser
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.