1. 进程与线程的基本概念解析
在C++编程中,进程和线程是并发编程的两个核心概念。理解它们的本质区别是写出高效并发程序的基础。
进程是操作系统资源分配的基本单位,每个进程都有独立的地址空间、文件描述符、环境变量等系统资源。当我们在Linux系统中运行./a.out或者在Windows中双击一个exe文件时,操作系统就会创建一个新的进程。进程之间相互隔离,一个进程崩溃通常不会影响其他进程。
线程则是CPU调度的基本单位,属于进程内部的执行流。同一个进程内的所有线程共享进程的地址空间和系统资源,但每个线程有自己的栈空间、寄存器状态和程序计数器。线程间的通信比进程间通信(IPC)更高效,但也更容易出现数据竞争等问题。
重要提示:在多核CPU上,操作系统可以真正并行地执行多个线程,而在单核CPU上,线程的"并行"实际上是通过时间片轮转实现的伪并行。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. C++中的线程操作实战
2.1 std::thread基础用法
C++11引入了<thread>头文件,使得线程操作变得非常简单。创建一个线程只需要实例化std::thread对象并传入可调用对象:
cpp复制#include <iostream>
#include <thread>
void hello() {
std::cout << "Hello from thread!\n";
}
int main() {
std::thread t(hello);
t.join(); // 等待线程结束
return 0;
}
在实际项目中,我经常遇到新手容易忽略的几个问题:
- 忘记调用join()或detach(),导致程序终止时std::thread析构函数抛出异常
- 在多线程中不加保护地访问共享数据
- 在线程函数中抛出异常但未捕获,导致程序崩溃
2.2 线程同步机制
当多个线程访问共享资源时,必须使用同步机制来避免竞态条件。C++提供了多种同步原语:
- 互斥量(std::mutex):最基本的同步机制
cpp复制std::mutex mtx;
void safe_increment(int& counter) {
std::lock_guard<std::mutex> lock(mtx);
++counter;
}
- 条件变量(std::condition_variable):用于线程间通信
cpp复制std::condition_variable cv;
std::mutex cv_mtx;
bool ready = false;
// 等待线程
std::unique_lock<std::mutex> lk(cv_mtx);
cv.wait(lk, []{return ready;});
// 通知线程
{
std::lock_guard<std::mutex> lk(cv_mtx);
ready = true;
}
cv.notify_one();
- 原子操作(std::atomic):对于简单数据类型,原子操作通常比互斥量更高效
cpp复制std::atomic<int> counter(0);
counter.fetch_add(1); // 原子递增
3. 进程操作与进程间通信
3.1 创建进程
在Unix-like系统中,可以使用fork()系统调用创建新进程:
cpp复制#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
execlp("/bin/ls", "ls", NULL);
} else if (pid > 0) {
// 父进程
wait(NULL); // 等待子进程结束
}
return 0;
}
Windows系统则使用CreateProcess API:
cpp复制#include <windows.h>
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;
CreateProcess(NULL, "notepad.exe", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3.2 进程间通信(IPC)方式
- 管道(Pipe):最简单的IPC方式,适用于父子进程
cpp复制int fd[2];
pipe(fd);
if (fork() == 0) {
close(fd[0]); // 关闭读端
write(fd[1], "hello", 6);
} else {
close(fd[1]); // 关闭写端
char buf[6];
read(fd[0], buf, 6);
}
- 共享内存:最高效的IPC方式,但需要同步机制配合
cpp复制// Unix共享内存示例
int shm_id = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
int* shared = (int*)shmat(shm_id, NULL, 0);
*shared = 42; // 写入共享内存
- 消息队列:结构化数据传输
- 套接字(Socket):可用于不同主机间的进程通信
4. 高级线程管理与性能优化
4.1 线程池实现
频繁创建销毁线程开销很大,线程池是常见的优化手段。C++17没有内置线程池,但我们可以自己实现一个简单版本:
cpp复制#include <vector>
#include <queue>
#include <functional>
#include <future>
class ThreadPool {
public:
ThreadPool(size_t threads) : stop(false) {
for(size_t i = 0; i < threads; ++i)
workers.emplace_back([this] {
for(;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if(this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type> {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
if(stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task](){ (*task)(); });
}
condition.notify_one();
return res;
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread &worker: workers)
worker.join();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
4.2 避免常见并发问题
- 死锁:当两个或多个线程互相等待对方释放锁时发生
cpp复制// 错误示例:可能导致死锁
void transfer(Account& from, Account& to, int amount) {
std::lock_guard<std::mutex> lock1(from.mtx);
std::lock_guard<std::mutex> lock2(to.mtx);
from.balance -= amount;
to.balance += amount;
}
// 正确做法:使用std::lock同时锁定多个互斥量
void safe_transfer(Account& from, Account& to, int amount) {
std::unique_lock<std::mutex> lock1(from.mtx, std::defer_lock);
std::unique_lock<std::mutex> lock2(to.mtx, std::defer_lock);
std::lock(lock1, lock2);
from.balance -= amount;
to.balance += amount;
}
-
ABA问题:在无锁编程中常见,可以通过带标记的指针或使用C++20的atomic_ref解决
-
虚假唤醒:条件变量可能在未被notify的情况下返回,因此必须使用谓词检查
cpp复制// 错误:可能虚假唤醒
cv.wait(lock);
// 正确:使用谓词检查
cv.wait(lock, []{ return data_ready; });
5. 现代C++并发新特性
5.1 C++20中的新特性
- std::jthread:可自动join的线程,比std::thread更安全
cpp复制std::jthread worker([]{
while(!std::this_thread::is_interruption_requested()) {
// 执行任务
}
});
// 析构时会自动调用request_stop()和join()
- std::atomic_ref:允许对非原子变量进行原子操作
cpp复制int data = 0;
std::atomic_ref<int> atomic_data(data);
atomic_data.store(42); // 原子操作
- std::latch和std::barrier:新的同步原语
5.2 协程(C++20)
虽然协程不是线程,但在异步编程中非常有用:
cpp复制#include <coroutine>
struct task {
struct promise_type {
task get_return_object() { return {}; }
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
task my_coroutine() {
std::cout << "Coroutine started\n";
co_await std::suspend_always{};
std::cout << "Coroutine resumed\n";
}
在实际项目中,我发现合理使用协程可以显著简化异步代码的逻辑,但需要注意:
- 协程有额外的内存开销
- 调试比普通函数更困难
- 不同编译器的实现可能有差异
