【Linux】创建线程
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
文章目录
一、为什么需要线程?
创建线程
示例:计算斐波恩夕法
一、为什么需要线程?
在多核处理器的计算机上,线程可以充分利用 CPU 资源,提高程序的执行效率。线程是轻量级的进程,创建和销毁的开销远小于进程,使得线程成为并发编程的首选。
创建线程
在 Linux 中,使用 pthread 库创建线程的基本步骤如下:
-
包含头文件:
#include <pthread.h>
-
定义线程函数: 线程函数是线程执行的入口点,它必须符合特定的函数签名。
void* thread_function(void* arg) {// 线程执行的代码return nullptr;
}
-
创建线程: 使用
pthread_create
函数创建线程,并将线程函数作为参数传递。
pthread_t thread;
int result = pthread_create(&thread, nullptr, thread_function, nullptr);
if (result != 0) {// 处理错误
}
-
等待线程结束: 使用
pthread_join
函数等待线程结束。
void* ret = nullptr;
pthread_join(thread, &ret);
-
销毁线程: 线程结束时,使用
pthread_exit
函数退出线程。
pthread_exit(nullptr);
示例:计算斐波恩夕法
下面是一个使用线程计算斐波那契数列的示例,展示了如何创建多个线程来并行计算。
#include <iostream>
#include <pthread.h>
#include <vector>void* calculate_fibonacci(int n) {std::cout << n << " = " " << n << std::endl;
}class Thread {
public:std: _func, const std::string &name = "None"): _name(name), _func(func), _is_running(false){}static void*start_routine(void *args) {Thread *self = static_cast<Thread *>(args);self->_is_running = true;self->_lwpid = get_lwp_id();self->_func();pthread_exit((void *)0);}void Start() {int n = pthread_create(&_tid, nullptr, start_routine, this);if (n == 0) {std::cout << "run thread success\n" << std::endl;}}void Join() {if (!_is_running){return;}int n = pthread_join(_tid, nullptr);if (n == 0) {std::cout << "pthread_join success" << std::endl;}}~Thread() {}private:bool _is_running;pthread_t _tid;pid_t _lwpid;std::string _name;func_t _func;
};using func_t = std::function<void()>;int main() {std::vector<int> numbers = {0, 1, 1, 2, 3, 5, 8, 13};Thread threads;for (auto num : numbers) {Thread t([= calculate, "Thread " + std::to_string(num)]);t.Start();threads.push_back(std::move(t));}for (auto& t : threads) {t.Join();}return 0;
}