2012-12-06 49 views
3

我想知道如何使用C語言在線程之間傳遞數據。使用C問題在線程之間傳遞數據

例如:X等待來自某處的消息。
Y向T-X發送有關事件的消息並等待響應。
T-X處​​理事件並向T-Y發送響應。
T-X等待另一條消息。

+1

Theads? pthreads?那麼你只需要使用相同的變量...例如靜態。線程共享相同的內存空間 – Kek

+0

帶有一些鎖定機制的全局變量? – Jeyaram

+0

聽起來像管道或插座是你在找什麼。檢查'pipe(2)'和'socketpair(3)'。或者,如果您正在尋找更高效但更少同步的用戶空間方式,那麼請查看虛擬環形緩衝區'vrb(3)'。 –

回答

2

取自https://computing.llnl.gov/tutorials/pthreads/#Mutexes並修改的示例程序。這表明,如何在多個線程中使用全局聲明的數據。

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

/* 
The following structure contains the necessary information 
to allow the function "dotprod" to access its input data and 
place its output into the structure. 
*/ 

typedef struct 
{ 
    double  *a; 
    double  *b; 
    double  sum; 
    int  veclen; 
} DOTDATA; 

/* Define globally accessible variables and a mutex */ 

#define NUMTHRDS 4 
#define VECLEN 100 

DOTDATA dotstr; //GLOBAL DATA which is going to be accessed by different threads 

pthread_t callThd[NUMTHRDS]; 
pthread_mutex_t mutexsum; 

void *dotprod(void *arg) 
{ 

    /* Define and use local variables for convenience */ 

    int i, start, end, len ; 
    long offset; 
    double mysum, *x, *y; 
    offset = (long)arg; 

    len = dotstr.veclen; 
    start = offset*len; 
    end = start + len; 
    x = dotstr.a; 
    y = dotstr.b; 

    /* 
    Perform the dot product and assign result 
    to the appropriate variable in the structure. 
    */ 

    mysum = 0; 
    for (i=start; i<end ; i++) 
    { 
     mysum += (x[i] * y[i]); 
    } 

    /* 
    Lock a mutex prior to updating the value in the shared 
    structure, and unlock it upon updating. 
    */ 
    pthread_mutex_lock (&mutexsum); 
    dotstr.sum += mysum; 
    pthread_mutex_unlock (&mutexsum); 

    pthread_exit((void*) 0); 
} 

int main (int argc, char *argv[]) 
{ 
    long i; 
    double *a, *b; 
    void *status;  

    /* Assign storage and initialize values */ 
    a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); 
    b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); 

    for (i=0; i<VECLEN*NUMTHRDS; i++) 
    { 
    a[i]=1.0; 
    b[i]=a[i]; 
    } 

    dotstr.veclen = VECLEN; 
    dotstr.a = a; 
    dotstr.b = b; 
    dotstr.sum=0; 

    pthread_mutex_init(&mutexsum, NULL);    

    for(i=0; i<NUMTHRDS; i++) 
     { 
    /* 
    Each thread works on a different set of data. 
    The offset is specified by 'i'. The size of 
    the data for each thread is indicated by VECLEN. 
    */ 
    pthread_create(&callThd[i], NULL, dotprod, (void *)i); 
    }  

    /* Wait on the other threads */ 
for(i=0; i<NUMTHRDS; i++) 
    { 
    pthread_join(callThd[i], &status); 
}  

    printf ("Sum = %f \n", dotstr.sum); 
    free (a); 
    free (b); 
    pthread_mutex_destroy(&mutexsum); 
    pthread_exit(NULL);//No need of pthread_join() if pthread_exit() used. 
} 
0

線程共享相同的內存空間,因此您可以使用普通變量在線程之間共享數據。

你也提到關於線程等待某個事件,這是另一個故事 - 同步。爲此,您可以使用互斥鎖作爲例子。