C++基础面试题, C++并发编程
C++基础面试题, C++并发编程
QA
Step 1
Q:: What is the difference between std::thread
and std::async
in C++?
A:: The std::thread
class represents a single thread of execution and allows you to create and manage threads explicitly. It requires the programmer to manage the thread’s lifecycle, including joining or detaching it.
std::async``, on the other hand, abstracts the creation and management of a new thread, potentially deferring execution until the result is needed.
std::async
also manages the synchronization of the result automatically, making it easier to use when you need to execute functions asynchronously without explicitly handling the thread.
Step 2
Q:: How does std::mutex
work in C++? Explain how it can be used to prevent data races.
A:: A std::mutex
is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads, which can lead to data races.
When a thread locks a mutex using lock()``, it gains exclusive access to the critical section of code. Other threads attempting to lock the same mutex will block until the mutex is unlocked. This ensures that only one thread at a time can execute the critical section, preventing concurrent access to shared resources.
Step 3
Q:: What are the advantages of using std::condition_variable
in multi-threaded programming?
A:: std::condition_variable
allows threads to be signaled when a particular condition is met. It enables threads to wait for a condition to become true without busy-waiting, which is inefficient. Instead, the thread releases the associated mutex and goes to sleep until it is notified by another thread, which then wakes it up to check the condition again. This is particularly useful for implementing producer-consumer patterns, where the producer thread signals the consumer thread that data is available.
Step 4
Q:: Explain RAII (Resource Acquisition Is Initialization) and its importance in C++.
A:: RAII is a programming idiom that binds the lifecycle of resources (such as memory, file handles, mutexes) to the lifetime of objects. In C++, resources are acquired in the constructor and released in the destructor of an object. This ensures that resources are automatically released when the object goes out of scope, preventing resource leaks and making exception-safe code easier to write. RAII is especially important in managing resources in concurrent programming to avoid deadlocks and ensure proper synchronization.