详细介绍:【Linux】创建线程

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

一、为什么需要线程?

在多核处理器的计算机上,线程可以充分利用 CPU 资源,提高程序的执行效率。线程是轻量级的进程,创建和销毁的开销远小于进程,使得线程成为并发编程的首选。

创建线程

在 Linux 中,使用 pthread 库创建线程的基本步骤如下:

  1. 包含头文件

#include
  1. 定义线程函数: 线程函数是线程执行的入口点,它必须符合特定的函数签名。

void* thread_function(void* arg) {
// 线程执行的代码
return nullptr;
}
  1. 创建线程: 使用 pthread_create 函数创建线程,并将线程函数作为参数传递。

pthread_t thread;
int result = pthread_create(&thread, nullptr, thread_function, nullptr);
if (result != 0) {
// 处理错误
}
  1. 等待线程结束: 使用 pthread_join 函数等待线程结束。

void* ret = nullptr;
pthread_join(thread, &ret);
  1. 销毁线程: 线程结束时,使用 pthread_exit 函数退出线程。

pthread_exit(nullptr);
示例:计算斐波恩夕法

下面是一个使用线程计算斐波那契数列的示例,展示了如何创建多个线程来并行计算。

#include
#include
#include
void* calculate_fibonacci(int n) {
std::cout (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 ;
int main() {
std::vector 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;
}

posted @ 2025-09-02 12:37  yfceshi  阅读(9)  评论(0)    收藏  举报