Linux 多线程创建基础
在Linux系统中,多线程编程主要基于POSIX线程(pthread)库实现。创建线程的核心函数是pthread_create,其原型如下:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg);
thread: 指向线程标识符的指针attr: 用于设置线程属性,通常置为NULL表示默认属性start_routine: 线程执行的函数入口arg: 传递给线程函数的参数
线程创建示例代码
以下是一个基本的多线程创建示例:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *thread_function(void *arg) {
int thread_id = *(int *)arg;
printf("Thread %d is running\n", thread_id);
return NULL;
}
int main() {
pthread_t threads[5];
int thread_args[5];
for (int i = 0; i < 5; i++) {
thread_args[i] = i;
if (pthread_create(&threads[i], NULL, thread_function, &thread_args[i])) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
线程封装技术
将线程功能封装成类可以提高代码的可重用性和安全性。以下是C++实现的线程封装示例:
#include <pthread.h>
#include <functional>
#include <memory>
class Thread {
public:
explicit Thread(std::function<void()> func) : func_(func) {}
~Thread() {
if (started_ && !joined_) {
pthread_detach(thread_);
}
}
void Start() {
started_ = true;
pthread_create(&thread_, nullptr, &Thread::ThreadRoutine, this);
}
void Join() {
if (started_ && !joined_) {
joined_ = true;
pthread_join(thread_, nullptr);
}
}
private:
static void* ThreadRoutine(void* arg) {
Thread* t = static_cast<Thread*>(arg);
t->func_();
return nullptr;
}
pthread_t thread_;
std::function<void()> func_;
bool started_ = false;
bool joined_ = false;
};
线程安全与同步机制
在多线程编程中,同步机制至关重要。常用的同步机制包括:
- 互斥锁(Mutex)
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
- 条件变量(Condition Variable)
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void wait() {
pthread_cond_wait(&cond, &mutex);
}
void notify() {
pthread_cond_signal(&cond);
}
线程池实现
线程池是高效管理多线程的技术,以下是一个简单的线程池实现框架:
#include <queue>
#include <vector>
#include <functional>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t thread_count) {
for (size_t i = 0; i < thread_count; ++i) {
workers.emplace_back([this] {
while (true) {
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>
void Enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(std::forward<F>(f));
}
condition.notify_one();
}
~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 = false;
};
线程调试与性能分析
调试多线程程序时,常用的工具包括:
- gdb:可以设置断点观察线程状态
- valgrind:检测内存泄漏和线程错误
- perf:分析线程性能瓶颈
- strace:跟踪线程系统调用
调试命令示例:
gdb -p <pid>
thread apply all bt
现代C++线程替代方案
C++11引入了<thread>头文件,提供了更高级的线程封装:
#include <thread>
#include <vector>
void worker(int id) {
// 线程工作内容
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back(worker, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}

被折叠的 条评论
为什么被折叠?



