Implementation of communication between two threads under Linux __linux

Source: Internet
Author: User

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; }  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.