Home  >  Article  >  Backend Development  >  How to create and manage threads in C++? What thread synchronization mechanisms are there?

How to create and manage threads in C++? What thread synchronization mechanisms are there?

王林
王林Original
2024-05-07 21:03:01510browse

Threads in C Threads are lightweight execution units that enable concurrent programming. Use the std::thread class to create threads and maintain the consistency of shared data through synchronization mechanisms such as mutex locks, condition variables, and spin locks. The practical case shows the process of using threads to calculate the sum concurrently.

C++ 中如何创建和管理线程?有哪些线程同步机制?

Thread creation and management in C

Threads are lightweight execution units that share the same address space with processes and can implement concurrent programming.

Creating a thread

In C, use the std::thread class to create a thread:

#include <thread>

void thread_function() {
  // 执行线程任务
}

int main() {
  std::thread thread(thread_function);
  thread.join();  // 阻塞主线程,直到线程执行完毕
  return 0;
}

Thread synchronization mechanism

is To maintain the consistency of shared data between threads, you need to use a synchronization mechanism:

Mutex (Mutex)

#include <mutex>

std::mutex mutex;

void thread_function() {
  std::lock_guard<std::mutex> lock(mutex);
  // 对共享数据进行操作
}

Condition Variable (Condition Variable)

#include <condition_variable>

std::condition_variable cv;
std::mutex cv_mutex;

void thread_function() {
  std::unique_lock<std::mutex> lock(cv_mutex);
  cv.wait(lock, [] { return condition_is_met; });
  // 条件满足时,继续执行
}

Spin lock (Spinlock)

#include <atomic>

std::atomic_flag spinlock = ATOMIC_FLAG_INIT;

void thread_function() {
  while (spinlock.test_and_set(std::memory_order_acquire));
  // 对共享数据进行操作
  spinlock.clear(std::memory_order_release);
}

Practical case

Concurrent calculation and summation

#include <thread>
#include <vector>

std::mutex sum_mutex;
long long sum = 0;

void add_numbers(const std::vector<int>& numbers) {
  for (int num : numbers) {
    std::lock_guard<std::mutex> lock(sum_mutex);
    sum += num;
  }
}

int main() {
  std::vector<std::thread> threads;
  std::vector<int> numbers = {...};  // 要相加的数字列表

  // 创建并执行线程
  for (size_t i = 0; i < std::thread::hardware_concurrency(); i++) {
    threads.emplace_back(add_numbers, numbers);
  }

  // 等待所有线程结束
  for (auto& thread : threads) {
    thread.join();
  }

  std::cout << "Sum: " << sum << std::endl;
  return 0;
}

The above is the detailed content of How to create and manage threads in C++? What thread synchronization mechanisms are there?. 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