簡體   English   中英

使用struct(pthread)將多個args傳遞給線程

[英]Pass multiple args to thread using struct (pthread)

我正在學習為加法器程序使用pthread進行編程,在引用了一些代碼后仍然無法使用結構體將多個參數傳遞給線程,這是我的越野車程序:

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

typedef struct s_addition {
    int num1;
    int num2;
    int sum;
} addition;


void *thread_add_function (void *ad)
{
    printf ("ad.num1:%d, ad.num2:%d\n",ad.num1, ad.num2);

    ad.sum = ad.num1 + ad.num2;
    pthread_exit(0);
}

int main()
{
    int N = 5;
    int a[N], b[N], c[N];
    srand (time(NULL));
    // fill them with random numbers
    for ( int j = 0; j < N; j++ ) {
        a[j] = rand() % 392;
        b[j] = rand() % 321;        
    }

    addition ad1;
    pthread_t thread[N];

    for (int i = 0; i < N; i++) {
        ad1.num1 = a[i];
        ad1.num2 = b[i];
        printf ("ad1.num1:%d, ad1.num2:%d\n",ad1.num1, ad1.num2);
        pthread_create (&thread[i], NULL, thread_add_function, &ad1);
        pthread_join(thread[i], NULL);
        c[i] = ad.sum;
    }

    printf( "This is the result of using pthread.\n");
    for ( int i = 0; i < N; i++) {
        printf( "%d + %d = %d\n", a[i], b[i], c[i]);
    }
}

但是在編譯時出現以下錯誤:

vecadd_parallel.c:15:39:錯誤:成員引用基本類型'void *'不是結構或聯合printf(“ ad.num1:%d,ad.num2:%d \\ n”,ad.num1,ad。 num2);

我嘗試過,但仍然看不到線索,這是我做錯了什么?

似乎您嘗試訪問void數據類型的成員時遇到問題。

您將需要添加一行以將參數thread_add_function轉換為正確的數據類型,類似於addition* add = (addition*)ad; thread_add_function ,然后用這個變量在你的函數(注意,你也必須改變你[R . “s至-> ,因為它是一個指針)

您還應該只將數據傳遞給malloc()的線程,因為堆棧分配的數據可能不是永久的。 對於當前的實現來說應該沒問題,但是以后進行更改很容易帶來奇怪的,不可預測的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM