Home  >  Article  >  Backend Development  >  How to perform concurrent programming in C++ code?

How to perform concurrent programming in C++ code?

WBOY
WBOYOriginal
2023-11-03 09:12:381332browse

How to perform concurrent programming in C++ code?

How to perform concurrent programming of C code?

With the development of computer technology, the application of multi-core processors and parallel computing is becoming more and more common. For program developers, how to utilize the parallel computing capabilities of multi-core processors to improve program performance has become an important topic. As a powerful programming language, C provides a wealth of tools and libraries for concurrent programming. This article will introduce how to perform concurrent programming in C code.

1. Threads and processes

In C, threads and processes can be used to implement concurrent programming. A thread is the execution unit of a program, and multiple threads can execute in parallel, while a process is an instance of a program, and different processes can execute in parallel. Parallel computing can be achieved by creating multiple threads or processes.

C provides multi-threading support, and you can use the std::thread class to create and manage threads. The following is a simple example:

#include <iostream>
#include <thread>

void hello() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(hello);
    t.join();
    return 0;
}

In this example, we create a thread named t, and then call its join() function to wait for the thread to complete execution. In this example, the thread function hello() outputs a message.

2. Mutex lock

In concurrent programming, when multiple threads access shared resources at the same time, data competition and uncertain behavior may occur. To avoid this situation, you can use a mutex to protect shared resources. C provides the std::mutex class for implementing mutex locks.

The following is an example of using a mutex lock:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;

void count() {
    std::lock_guard<std::mutex> lock(mtx);
    for (int i = 0; i < 10; ++i) {
        std::cout << i << std::endl;
    }
}

int main() {
    std::thread t1(count);
    std::thread t2(count);
    t1.join();
    t2.join();
    return 0;
}

In this example, we create two threads t1 and t2, which access a loop counter at the same time. In order to ensure the security of concurrent access, we use a mutex lock mtx. The std::lock_guard class is a RAII (resource acquisition i.e. initialization) class used to automatically release locks.

3. Condition variables

In concurrent programming, communication and synchronization between threads are sometimes required. C provides condition variables (condition_variable) to implement thread waiting and waking up.

The following is an example of using condition variables:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return ready; });
    std::cout << "Worker thread is running!" << std::endl;
}

int main() {
    std::thread t(worker);
    std::this_thread::sleep_for(std::chrono::seconds(2));
    
    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
    }
    cv.notify_one();
    
    t.join();
    return 0;
}

In this example, we create a thread t that waits for the value of the ready variable to be true. In the main thread, we wait for 2 seconds, set ready to true, and notify the t thread through the notify_one() function of the condition variable cv.

4. Concurrent containers

C provides some concurrent container classes, such as std::list, std::queue, std::map, etc., for safely running multiple threads Access and modify elements in the container.

The following is an example of using concurrent queue std::queue:

#include <iostream>
#include <thread>
#include <queue>

std::queue<int> q;
std::mutex mtx;

void producer() {
    for (int i = 0; i < 10; ++i) {
        std::lock_guard<std::mutex> lock(mtx);
        q.push(i);
    }
}

void consumer() {
    while (true) {
        std::lock_guard<std::mutex> lock(mtx);
        if (!q.empty()) {
            int value = q.front();
            q.pop();
            std::cout << "Consumed: " << value << std::endl;
        }
        else {
            break;
        }
    }
}

int main() {
    std::thread t1(producer);
    std::thread t2(consumer);
    t1.join();
    t2.join();
    return 0;
}

In this example, we create a producer thread and a consumer thread. The producer thread adds elements to the queue, and the consumer thread takes elements from the queue for consumption. In order to ensure the security of concurrent access, we use the mutex lock mtx.

Summary:

Through concurrent programming of threads and processes, you can make full use of the parallel computing capabilities of multi-core processors and improve program performance. C provides a wealth of tools and libraries, such as std::thread, std::mutex, std::condition_variable and concurrent containers, for implementing concurrent programming. When performing concurrent programming, you need to pay attention to data competition and synchronization issues to avoid the occurrence of uncertain behavior. In practical applications, choosing an appropriate concurrent programming solution based on specific needs can further improve program performance.

The above is the detailed content of How to perform concurrent programming in C++ code?. 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