117.info
人生若只如初见

如何传递参数给pthread_create

在C语言中,通过pthread_create()函数创建一个线程时,需要传递一个指向函数的指针作为第一个参数,该函数称为线程入口函数

#include 
#include 
#include 

// 线程入口函数
void *my_thread(void *arg) {
    int *num = (int *)arg; // 从参数中获取整数
    printf("Hello from thread %d\n", *num);
    return NULL;
}

int main() {
    pthread_t thread1, thread2;
    int num1 = 1, num2 = 2;

    // 使用参数创建线程
    if (pthread_create(&thread1, NULL, my_thread, (void *)&num1) != 0) {
        perror("Error creating thread 1");
        exit(EXIT_FAILURE);
    }

    if (pthread_create(&thread2, NULL, my_thread, (void *)&num2) != 0) {
        perror("Error creating thread 2");
        exit(EXIT_FAILURE);
    }

    // 等待线程结束
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    return 0;
}

在这个示例中,我们创建了两个线程thread1thread2,并分别传递了两个整数num1num2作为参数。线程入口函数my_thread()接收一个void *类型的参数,我们将其转换为int *类型,以便获取传递给线程的整数值。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fed77AzsKAANVA1Q.html

推荐文章

  • linux搭建gitlab有哪些步骤

    在Linux系统上搭建GitLab涉及多个步骤,包括准备工作、安装依赖、配置服务器、下载并安装GitLab软件包、启动GitLab服务以及访问GitLab。以下是详细的步骤说明:<...

  • linux搭建gitlab难不难

    在Linux上搭建GitLab是一个相对直接的过程,但需要一定的系统管理知识。以下是基于不同Linux发行版的安装步骤和注意事项:
    Ubuntu/Debian 安装步骤: 更新系...

  • linux搭建gitlab支持多用户吗

    是的,Linux上搭建的GitLab支持多用户 安装GitLab:首先,你需要在Linux服务器上安装GitLab。你可以按照GitLab官方文档中的说明进行安装:https://about.gitlab....

  • linux搭建gitlab怎样备份数据

    在Linux上搭建GitLab并备份数据,可以按照以下步骤进行:
    1. 安装GitLab
    首先,确保你的Linux系统已经安装了必要的依赖包。以Debian/Ubuntu为例:

  • linux pthread_create怎么用

    pthread_create是Linux操作系统中用于创建新线程的函数
    #include #include #include // 定义一个将要在线程中执行的功能
    void *print_hello(void *arg...

  • 能删除linux时间戳吗

    在Linux中,你可以使用date命令和-d选项来显示或设置系统时间,但它本身并不提供直接删除时间戳的功能。如果你想要删除或清除某个文件的时间戳,可以使用touch命...

  • 怎样同步linux时间戳

    要在Linux中同步时间戳,您可以使用以下方法: 使用NTP(网络时间协议)服务: NTP是一种用于同步计算机时间的协议。要在Linux系统中设置和使用NTP服务,请按照以...

  • linux时间戳会溢出吗

    Linux时间戳是基于秒的,从1970年1月1日(UTC/GMT的午夜)开始计算
    在64位系统中,时间戳使用64位整数表示,因此可以表示到公元292,277,026,596年。这意味着...