在 Ubuntu 下使用 GCC 进行多线程编程,通常有两种常见方式:
std::thread)下面分别说明,并给出编译命令和示例。
sudo apt update
sudo apt install build-essential
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* thread_func(void* arg) {
int id = *(int*)arg;
printf("Thread %d is running\n", id);
sleep(1);
printf("Thread %d finished\n", id);
return NULL;
}
int main() {
pthread_t t1, t2;
int a = 1, b = 2;
pthread_create(&t1, NULL, thread_func, &a);
pthread_create(&t2, NULL, thread_func, &b);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Main thread done\n");
return 0;
}
-pthread)gcc pthread_demo.c -o pthread_demo -pthread
./pthread_demo
✅ 注意:
-pthread,不是 -lpthread(虽然有时也能用,但 -pthread 更安全)std::thread#include <iostream>
#include <thread>
void func(int id) {
std::cout << "Thread " << id << " running\n";
}
int main() {
std::thread t1(func, 1);
std::thread t2(func, 2);
t1.join();
t2.join();
std::cout << "Main thread done\n";
return 0;
}
g++ thread_demo.cpp -o thread_demo -std=c++11 -pthread
./thread_demo
-pthread会出现类似错误:
undefined reference to `pthread_create'
✅ 解决:
gcc xxx.c -pthread
nproc
pthread_create / joinpthread_mutex_tpthread_cond_tstd::mutex, std::condition_variable如果你愿意,我可以:
你想学哪一个?