Home  >  Article  >  Backend Development  >  The key concept of C++ multi-threaded programming is how to synchronize threads?

The key concept of C++ multi-threaded programming is how to synchronize threads?

WBOY
WBOYOriginal
2024-06-03 11:55:56405browse

C++ Multi-thread synchronization key concepts: Mutex lock: ensure that the critical section can only be accessed by one thread. Condition variables: Threads can be awakened when specific conditions are met. Atomic operation: an uninterruptible single CPU instruction to ensure the atomicity of shared variable modifications.

C++ 多线程编程的关键概念是如何同步线程的?

Key concepts of C++ multi-threaded programming: Thread synchronization

Thread synchronization is a crucial part of multi-threaded programming , which ensures that multiple threads can safely access shared resources, avoiding contention and data corruption. The following introduces the key concepts of thread synchronization in C++:

Mutex lock:

Mutex lock (mutex) is an access control mechanism that allows only There can be one thread accessing the critical section, that is, the code area that needs to be accessed synchronously. Using a mutex lock can prevent multiple threads from modifying shared variables at the same time, causing data corruption.

std::mutex mtx;  // 定义互斥锁对象

void someFunction() {
    std::lock_guard<std::mutex> lock(mtx);  // 在进入临界区前加锁
    // 访问临界区代码
}

Condition variable:

Condition variable allows a thread to be awakened when specific conditions are met. This is useful in cooperative multithreaded programming, such as when one thread is waiting for another thread to produce data.

std::condition_variable cv;  // 定义条件变量对象
std::mutex mtx;  // 关联的互斥锁对象

void produce() {
    std::lock_guard<std::mutex> lock(mtx);  // 加锁
    // 产生数据
    cv.notify_all();  // 通知所有等待此条件的线程
}

void consume() {
    std::unique_lock<std::mutex> lock(mtx);  // 加锁
    cv.wait(lock);  // 等待 `produce()` 函数生产数据
    // 消费数据
}

Atomic operations:

Atomic operations are single CPU instructions that cannot be interrupted by other threads, ensuring that modifications to shared variables are atomic.

std::atomic<int> count;  // 定义原子变量

void incrementCount() {
    count++;  // 原子方式增加 `count`
}

Practical case:

Consider the following multi-threaded program:

std::vector<int> numbers;  // 共享的整型数组

void addNumber(int n) {
    numbers.push_back(n);
}

int main() {
    std::thread t1(addNumber, 1);
    std::thread t2(addNumber, 2);
    t1.join();
    t2.join();
    
    std::cout << "Numbers in the vector: ";
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

In this example, the numbers array is shared Resources that multiple threads can access concurrently. If synchronization measures are not taken, race conditions may occur, resulting in data corruption.

In order to access the array safely, we can use a mutex lock:

void addNumber(int n) {
    std::lock_guard<std::mutex> lock(mtx);  // 在访问数组前加锁
    numbers.push_back(n);
}

In this way, only one thread can access the array at a time, ensuring data integrity.

Output:

Numbers in the vector: 1 2 

The above is the detailed content of The key concept of C++ multi-threaded programming is how to synchronize threads?. 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