温馨提示×

linux中pthread_create怎么传递参数

小亿
97
2023-12-21 17:28:11
栏目: 编程语言

在Linux中,使用pthread_create函数创建线程时,可以通过将参数传递给线程函数来传递参数。以下是pthread_create函数的原型:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);

其中,start_routine是线程函数的指针,它接受一个void*类型的参数,并返回一个void*类型的结果。arg参数就是要传递给线程函数的参数。

在创建线程时,可以将要传递的参数作为arg参数传递给pthread_create函数。在线程函数中,可以将arg参数转换为正确的类型,然后使用它。

以下是一个示例代码,演示如何使用pthread_create函数传递参数:

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

// 线程函数
void *my_thread_func(void *arg) {
    int my_arg = *((int*)arg);
    printf("Received argument: %d\n", my_arg);
    
    // 具体的线程逻辑
    // ...
    
    // 线程结束时,可以通过返回一个值来传递结果
    // return result;
}

int main() {
    pthread_t thread;
    int arg = 42; // 要传递的参数

    // 创建线程,并将参数传递给线程函数
    if (pthread_create(&thread, NULL, my_thread_func, (void*)&arg) != 0) {
        printf("Failed to create thread\n");
        return 1;
    }

    // 等待线程结束
    if (pthread_join(thread, NULL) != 0) {
        printf("Failed to join thread\n");
        return 1;
    }

    return 0;
}

在上面的示例代码中,arg变量是要传递给线程函数my_thread_func的参数。在pthread_create函数调用时,使用&arg将其地址传递给arg参数。然后在线程函数中,将arg参数转换为int类型,并使用它。

0