在 Linux 下用 C++ 实现多线程,常见方式有两种:
std::thread(推荐,跨平台)下面分别说明,并给示例。
std::thread(推荐)#include <iostream>
#include <thread>
void worker(int id) {
std::cout << "Thread " << id << " is running\n";
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
return 0;
}
编译(必须加 -pthread):
g++ main.cpp -std=c++11 -pthread -o test
std::thread t([] {
std::cout << "Lambda thread\n";
});
t.join();
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int count = 0;
void worker() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx);
++count;
}
}
int main() {
std::thread t1(worker);
std::thread t2(worker);
t1.join();
t2.join();
std::cout << count << std::endl;
}
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void consumer() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return ready; });
std::cout << "Consumer got signal\n";
}
void producer() {
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
}
int main() {
std::thread c(consumer);
std::thread p(producer);
c.join();
p.join();
}
#include <pthread.h>
#include <iostream>
void* worker(void* arg) {
int id = *(int*)arg;
std::cout << "Thread " << id << std::endl;
return nullptr;
}
int main() {
pthread_t t1, t2;
int a = 1, b = 2;
pthread_create(&t1, nullptr, worker, &a);
pthread_create(&t2, nullptr, worker, &b);
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
}
编译:
g++ pthread_test.cpp -pthread -o test
| 场景 | 推荐 |
|---|---|
| 新项目 / 跨平台 | std::thread |
| 底层 Linux 开发 | pthread |
| 高性能服务器 | pthread / std::thread + 线程池 |
join() 或 detach()如果你需要:
可以继续问我。