21xrx.com
2025-03-26 14:21:16 Wednesday
文章检索 我的文章 写文章
C++中的线程:多线程编程的基础知识
2023-07-07 18:31:29 深夜i     13     0
C++ 线程 多线程编程 基础知识

在计算机领域中,线程是指一个程序内部的执行流,它可以与其他线程并行执行,从而增加程序的并发性,提高计算机的效率。C++语言中的线程是用于多线程编程的基础之一,掌握C++中的线程编程是程序员必备的技能。

C++11标准中提供了对线程的支持,包含标准库 。C++中的线程可以使用std::thread类创建,该类提供了一系列的构造函数和成员函数,用于控制线程的创建、运行和销毁。在创建线程时,我们需要将要执行的函数作为参数传递给std::thread对象,并使用其实例的方法begin()和join()来控制线程的开始和结束。

下面是一个简单的例子,演示了如何使用C++中的线程来创建两个线程并让它们执行两个不同的任务。

#include <iostream>
#include <thread>
 
void thread_function1()
{
  std::cout<<"Thread 1 is running\n";
}
 
void thread_function2()
{
  std::cout<<"Thread 2 is running\n";
}
 
int main()
{
  std::thread t1(thread_function1); // thread t1 starts execution
  std::thread t2(thread_function2); // thread t2 starts execution
 
  t1.join(); // main thread waits for the t1 to finish
  t2.join(); // main thread waits for the t2 to finish
 
  return 0;
}

该程序创建了两个线程,其中一个线程执行函数thread_function1,另一个线程执行函数thread_function2。在主线程中,我们使用了std::thread实例的join()方法等待线程的结束,确保程序正确执行。

此外,C++中还提供了互斥锁和条件变量,可以利用它们来实现线程之间的同步和通信。互斥锁是一种同步机制,它是用来保护共享资源,以避免多个线程同时访问同一个资源,从而导致资源的不一致。条件变量是一种通信机制,它用于在线程之间传递信号和信息,使得线程可以按照某种特定的顺序运行。

下面是一个示例程序,演示了如何使用互斥锁和条件变量来实现线程之间的同步。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
 
std::condition_variable cv;
std::mutex mutex;
bool is_ready = false;
 
void worker_thread()
{
  std::unique_lock<std::mutex> lock(mutex);
  cv.wait(lock, [] return is_ready; );
 
  std::cout<<"Worker thread is processing data\n";
}
 
int main()
{
  std::thread worker(worker_thread);
 
  // main thread is doing some work
  std::this_thread::sleep_for(std::chrono::seconds(3));
 
  {
    std::lock_guard<std::mutex> lock(mutex);
    is_ready = true;
  }
  cv.notify_all();
 
  worker.join();
 
  return 0;
}

该程序创建了一个工作线程worker_thread,主线程通过互斥锁和条件变量的组合来控制工作线程的执行。在工作线程中,我们使用std::unique_lock和std::condition_variable实现了等待主线程的信号,并在接收到信号后执行相应的任务。

C++中的线程提供了高效、并发的编程方式,可以极大地提高计算机的运行效率。通过掌握C++中的线程编程技能,我们可以开发更加高效、精准的计算机应用,并为自己的编程生涯打下坚实的基础。

  
  

评论区