入门 Linux 下 C++ 并发编程,可以按“基础 → 系统 → 标准库 → 实战”的路径来走。下面给你一份比较清晰的学习路线和资源建议。
确保你熟悉:
推荐:
理解“为什么需要并发”:
推荐了解:
ps, top, htopstrace, lsof先用 pthread 理解线程本质:
#include <pthread.h>
#include <iostream>
void* thread_func(void* arg) {
std::cout << "Hello from thread\n";
return nullptr;
}
int main() {
pthread_t t;
pthread_create(&t, nullptr, thread_func, nullptr);
pthread_join(t, nullptr);
}
编译:
g++ test.cpp -pthread
学习重点:
pthread_createpthread_joinmutexcond推荐:
man pthread_createstd::thread现代 C++ 推荐从这里开始:
#include <thread>
#include <iostream>
void foo() {
std::cout << "thread\n";
}
int main() {
std::thread t(foo);
t.join();
}
std::mutexstd::lock_guardstd::unique_lockstd::condition_variable示例:
std::mutex m;
std::condition_variable cv;
bool ready = false;
void worker() {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, []{ return ready; });
}
std::atomicstd::asyncstd::futurestd::promise建议自己实现:
这是“真正理解并发”的转折点。
gdb / gdb multi-threadvalgrind --tool=helgrindperfthread sanitizer:g++ -fsanitize=thread
如果你愿意,我可以:
你更想从哪一步开始?