Skip to content

Instantly share code, notes, and snippets.

@Garciat
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Garciat/86b05d0ace8e4e0ebbdc to your computer and use it in GitHub Desktop.
Save Garciat/86b05d0ace8e4e0ebbdc to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
long ntimes = 0;
char data[] = {'0', '1'};
// llamadas de sistemas utilizadas:
// write, pthread_create, pthread_join, pthread_exit, exit
void* writer(void *arg) {
for (int i = 0; i < ntimes; ++i) {
// (1 !=) porque escribe 1 byte
if (1 != write(STDOUT_FILENO, arg, 1)) {
fprintf(stderr, "Fallo la escritura\n");
pthread_exit(NULL);
}
}
return arg;
}
// OJO **siempre** verificar la respuesta
// de una llamada de sistema.
// leer las man pages de cada llamada
// de funcion utilizada y ver que codigos
// de error puede devolver para actuar
// segun corresponda
// http://man7.org/linux/man-pages/index.html
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s NTIMES\n", argv[0]);
// exit hace flush streams de stdio
exit(EXIT_FAILURE);
}
ntimes = strtol(argv[1], NULL, 10);
pthread_t t1, t2;
if (0 != pthread_create(&t1, NULL, writer, &data[0])) {
fprintf(stderr, "No se pudo crear hilo 1.\n");
exit(EXIT_FAILURE);
}
if (0 != pthread_create(&t2, NULL, writer, &data[1])) {
fprintf(stderr, "No se pudo crear hilo 2.\n");
exit(EXIT_FAILURE);
}
if (0 != pthread_join(t1, NULL)) {
fprintf(stderr, "No se pudo esperar hilo 1.\n");
exit(EXIT_FAILURE);
}
if (0 != pthread_join(t2, NULL)) {
fprintf(stderr, "No se pudo esperar hilo 2.\n");
exit(EXIT_FAILURE);
}
putchar('\n');
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment