/*
 * cv2.c
 * 
 * Copyright 2026 osboxes <osboxes@osboxes>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * uso simple de variable de condicion
 * proceso en loop permanente
 * detener con Ctrl+C
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <pthread.h>

void *hijoA(void *p);
void *hijoB(void *p);

char letra;
int llegue_a_z = 0;

pthread_mutex_t m1;// = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  v1;// = PTHREAD_COND_INITIALIZER;

int main(int argc, char **argv) {
	pthread_t hiloA, hiloB;
	
	pthread_mutex_init(&m1, NULL);
    pthread_cond_init(&v1, NULL);
    
    int rc;
	rc = pthread_create(&hiloA,NULL,hijoA,NULL);
	rc = pthread_create(&hiloB,NULL,hijoB,NULL);
	rc=pthread_join(hiloA,NULL);
	rc=pthread_join(hiloB,NULL);
	printf("main(): rc=%d fin\n",rc);
	return 0;
}

void *hijoA(void *p) {  // hilo que imprime letras mayusculas
	do {
		letra='A';
		while(letra <= 'Z') {
			pthread_mutex_lock(&m1);
				printf("hijoA(): %c\n",letra);
				letra++;

				if ( letra == 'Z' ) {
					llegue_a_z=1;
					printf("hijoA(): signal de v1!\n");
					pthread_cond_signal(&v1);
				}
			pthread_mutex_unlock(&m1);
			usleep(50000);
		}
	} while(1);
	pthread_exit(NULL);
}

void *hijoB(void *p) {
	do {
		printf("hijoB(): inicio\n");
		pthread_mutex_lock(&m1);
			if ( !llegue_a_z ) {
				printf("hijoB(): no llegue a Z, hago wait\n");
				pthread_cond_wait(&v1, &m1);
				printf("hijoB(): llegue_a_z=%d fin wait\n",llegue_a_z);
				llegue_a_z = 0;
			}
			printf("hijoB(): letra paso por Z!\n");
		pthread_mutex_unlock(&m1);
	} while(1);
	pthread_exit(NULL);
} 
