Flow chart:
compile with GCC (gcc-pthread filename.c) ...
#include <stdio.h> #include <memory.h> #include <pthread.h> int buf[1000000]; int w=0,r=0; R is read pointer, w is write pointer int size=10; Buffer size pthread_mutex_t lock; Lock pthread_cond_t Is_empty; Whether the buffer is an empty pthread_cond_t is_full; Buffer is full void *sender (void *a)//Send 100 data {int i,j,k; for (i=1;i<=100;i++)//Total 100 Data {Pthread_mutex_lock (&lock) ; Whether the lock if (w-r>size)//buffer is full pthread_cond_wait (&is_full,&lock); Full, waiting for the receiving thread to take the data away buf[w++]=i; Buffer has space to send printf ("%d--->/n", i); Print out pthread_cond_signal (&is_empty); There is at least one data in the buffer, and the read thread can take him away from Pthread_mutex_unlock (&lock); Unlock} return; } void *receiver (void *a)//Accept data {int x; while (1) {pthread_mutex_lock (&lock);//Lock if (R==W)//buffer has data pthread_cond_w AIT (&is_empty,&lock); No data, waiting to send line Cheng data x=buf[r++]; There is data, take away if (x!=0) printf ("--->%d/n", x); Print out else break; Data sent-> accepted, end thread pthread_cond_signal (&is_full); There is at least one space in the buffer to allow the sending process to send data pthread_mutex_unlock (&lock); Unlock} return; int main () {memset (Buf,0,sizeof (BUF)); pthread_t a,b; Create two threads//Initialize Pthread_mutex_init (&lock,null); Pthread_cond_init (&is_full,null); Pthread_cond_init (&is_empty,null); The thread begins to work pthread_create (&a,null,sender,0); Pthread_create (&b,null,receiver,0); void *recycle; At the end of the thread, the collected data is stored Pthread_join (a,&recycle); Recycling Resources Pthread_join (b,&recycle); Recovery resources return 0; }