Generation

code to explanationTue, 25 Apr 2023

#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> int file_descriptor[2]; void* consumer(void p) { int receive_result; int received_value; while(1) { receive_result = read(file_descriptor[0], &received_value, 4); if(receive_result != 4) { printf("Consumer: A aparut o eroare la receptionarea datelor! \n"); pthread_exit(NULL); } printf("Consumer: Am primit valoarea: %d\n", received_value); } } void producer(void *p) { int send_result; int value_to_send = 1; while(1) { send_result = write(file_descriptor[1],&value_to_send, 4); if(send_result != 4) { printf("Producer: A aparut o eroare la trimiterea datelor prin pipe! \n"); pthread_exit(NULL); } printf("Producer: Am trimis valoarea: %d \n", value_to_send); value_to_send+=1; sleep(3); } } int main() { pthread_t t1,t2; int result; result = pipe(file_descriptor); if(result < 0) { printf("A aparut o eroare la adaugarea pipe-ului! \n"); return 0; } pthread_create(&t1, NULL, &consumer, NULL); pthread_create(&t2, NULL, &producer, NULL); pthread_join(t1,NULL); pthread_join(t2,NULL); return 0; }

The producer is in charge with generating the numbers to be sent to the consumer. The consumer receives the numbers, one by one and prints them.

Want to kickstart your project?Use the new AI Studio to create your code