Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

linux多线程

作者:花小泽ノ   发布日期:2026-07-28   浏览:52

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define NUM_THREADS 5

void *print_hello(void *thread_id) {
    long tid;
    tid = (long)thread_id;
    printf("Hello World! It's me, thread #%ld!\n", tid);
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[NUM_THREADS];
    int rc;
    long t;

    for (t = 0; t < NUM_THREADS; t++) {
        printf("In main: creating thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, print_hello, (void *)t);
        if (rc) {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    /* 等待所有线程完成 */
    for (t = 0; t < NUM_THREADS; t++) {
        pthread_join(threads[t], NULL);
    }

    printf("All threads completed. Exiting.\n");
    pthread_exit(NULL);
}

解释说明:

  1. 头文件引入#include <pthread.h> 引入了 POSIX 线程库的头文件,用于创建和管理线程。
  2. 宏定义#define NUM_THREADS 5 定义了线程的数量为 5。
  3. 线程函数void *print_hello(void *thread_id) 是每个线程执行的函数。它接收一个参数 thread_id 并打印一条消息。
  4. 主函数
    • 创建一个数组 pthread_t threads[NUM_THREADS] 来存储线程 ID。
    • 使用 for 循环创建多个线程,每个线程调用 print_hello 函数。
    • 检查 pthread_create 的返回值,如果有错误则退出程序。
    • 使用 pthread_join 等待所有线程完成。
  5. 结束:当所有线程完成后,主函数打印一条消息并退出。

这个示例展示了如何在 Linux 下使用 POSIX 线程库创建和管理多线程程序。

上一篇:linux zip 压缩命令

下一篇:linux将文件夹权限给用户

大家都在看

linux如何启动nginx

linux常用命令查询端口是否正常

linux 发送邮件

linux长ping命令

linux groupadd

linux关机命令行

linux 安装 gcc

linux重启oracle命令

linux把一个文件夹移动到另一个文件夹里

linux删除docker

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站