Linux上でpthread_createを使用して引数を渡す方法は何ですか?

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は、スレッド関数に渡す引数です。

スレッドを作成する際に、pthread_create関数に渡すargパラメーターとして渡すことができます。スレッド関数で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型に変換して使用します。

bannerAds