使用C问题在线程之间传递数据

我想知道如何使用C语言在线程之间传递数据。

例如:X等待来自某个地方的消息。
Y向TX发送有关事件的消息并等待响应。
TX处理事件并向TY发送响应。
TX等待另一条消息。

一个示例程序取自https://computing.llnl.gov/tutorials/pthreads/#Mutexes并进行了修改。 这表明了如何在多个线程中使用全局声明的数据。

 #include  #include  #include  /* 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 

线程共享相同的内存空间,因此您可以使用普通变量在线程之间共享数据。

你还提到线程等待某个事件,这是另一个故事 – 同步。 为此,您可以使用互斥锁。