Home  >  Article  >  Backend Development  >  Thread safety in C++ memory management

Thread safety in C++ memory management

PHPz
PHPzOriginal
2024-05-02 16:06:01396browse

Thread-safe memory management in C guarantees data integrity by ensuring that no data corruption or race conditions occur when multiple threads access shared data simultaneously. Key Takeaway: Use smart pointers such as std::shared_ptr and std::unique_ptr for thread-safe dynamic memory allocation. Use a mutex (such as std::mutex) to protect shared data from simultaneous access by multiple threads. Practical cases use shared data and multi-thread counters to demonstrate the application of thread-safe memory management.

C++ 内存管理中的线程安全

C Thread safety in memory management

Thread safety means that when multiple threads access shared data at the same time, no data corruption or competition will occur Conditional issues. In C, memory management is crucial when using multithreading as it involves shared data and synchronized access.

Dynamic Memory Allocation

In C, use the new and delete operators for dynamic memory allocation. However, these operators themselves are not thread-safe:

int *ptr = new int;
delete ptr;

If multiple threads use this code at the same time, it may cause use-after-free problems or double-free problems.

Thread-safe dynamic memory allocation

To ensure thread-safe dynamic memory allocation, the C standard library provides some thread-safe alternatives:

  • std::shared_ptr: A smart pointer that can be safely shared by multiple threads at the same time. It uses reference counting to track the extent of sharing and frees the memory when no threads are referencing the pointer anymore.
  • std::unique_ptr: A smart pointer that can only be owned by one thread. It releases memory as soon as the object is no longer needed.

Example: Thread-safe shared resources

Consider a class that contains a shared resource (such as statistics):

class SharedData {
public:
  std::mutex mtx; // 互斥锁
  int count = 0;

  void increment() {
    std::lock_guard<std::mutex> lock(mtx); // 获取互斥锁
    ++count;
  }
};

This class uses a mutex lock mtx to protect shared data to ensure that the count is not corrupted when multiple threads access the increment() method at the same time.

Practical case: Multi-threaded counter

The following is a practical case that demonstrates how to use thread-safe dynamic memory allocation and synchronization:

#include <iostream>
#include <thread>
#include <vector>
#include <memory>

std::shared_ptr<SharedData> sharedData = std::make_shared<SharedData>();

void incrementThread() {
  for (int i = 0; i < 1000000; ++i) {
    sharedData->increment();
  }
}

int main() {
  std::vector<std::thread> threads;
  for (int i = 0; i < 10; ++i) {
    threads.emplace_back(incrementThread);
  }

  for (auto &thread : threads) {
    thread.join();
  }

  std::cout << "Final count: " << sharedData->count << std::endl;

  return 0;
}

This program creates shared data and Reference it as std::shared_ptr. It then creates 10 threads, each of which increments the counter 1,000,000 times. The main thread waits for all threads to finish and finally prints the final count.

The above is the detailed content of Thread safety in C++ memory management. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn