Ferramentas do usuário

Ferramentas do site


threads_posix

Diferenças

Aqui você vê as diferenças entre duas revisões dessa página.


threads_posix [2023/09/12 16:14] (atual) – criada - edição externa 127.0.0.1
Linha 1: Linha 1:
 +====== Threads POSIX ======
 +
 +
 +Compilação de um programa C com suporte as threads POSIX:  ''gcc teste_thread.c -oteste_thread -lpthread''
 +
 +===== Funções =====
 +
 +  * [[pthread_detach]]
 +  * [[pthread_self]]
 +  * [[pthread_exit]]
 +  * [[pthread_create]]
 +  * [[pthread_join]]
 +  * [[pthread_mutex_lock]]
 +  * [[pthread_mutex_lock]]
 +
 +===== Concorrência entre threads =====
 +Este programa não implementa a concorrência de acesso a variável ''iContador''. Compile e execute este programa várias vezes para perceber o erro.
 +
 +<code c>
 +#include <sys/types.h>
 +#include <sys/socket.h>
 +#include <netinet/in.h>
 +#include <arpa/inet.h>
 +#include <unistd.h>
 +
 +#include <pthread.h>
 +
 +#define LOOP 50
 +
 +int iContador;
 +
 +void * teste_thread(void * pArg )
 +{
 +   int i, old;
 +   for( i = 0; i < LOOP; i++)
 +   {
 +      old = iContador;
 +      printf("\n%d: %d", pthread_self(), old);
 +      iContador = old + 1;
 +   }
 +   pthread_exit(0);
 +}
 +
 +int main(void)
 +{
 +   pthread_t tidA, tidB;
 +
 +   iContador = 0;
 +
 +   pthread_create(&tidA, NULL, teste_thread, NULL);
 +   pthread_create(&tidB, NULL, teste_thread, NULL);
 +
 +   printf("\nEsperando A terminar");
 +   pthread_join(tidA, NULL);
 +   printf("\nEsperando B terminar");
 +   pthread_join(tidB, NULL);
 +
 +   return 0;
 +}
 +</code>
 +
 +Este programa implementa a concorrência de acesso a variável ''iContador''. Compile e execute este programa várias vezes e você perceberá que não ocorrerá erro.
 +<code c>
 +#include <stdio.h>
 +#include <stdlib.h>
 +#include <string.h>
 +#include <errno.h>
 +#include <sys/types.h>
 +#include <sys/socket.h>
 +#include <netinet/in.h>
 +#include <arpa/inet.h>
 +#include <unistd.h>
 +
 +#include <pthread.h>
 +
 +#define LOOP 50
 +
 +pthread_mutex_t contador_mutex = PTHREAD_MUTEX_INITIALIZER;
 +int iContador;
 +
 +void * teste_thread(void * pArg )
 +{
 +   int i, old;
 +   for( i = 0; i < LOOP; i++)
 +   {
 +      pthread_mutex_lock(&contador_mutex);
 +      old = iContador;
 +      printf("\n%d: %d", pthread_self(), old+1);
 +      iContador = old + 1;
 +      pthread_mutex_unlock(&contador_mutex);
 +      sleep(1);
 +   }
 +   pthread_exit(0);
 +}
 +
 +int main(void)
 +{
 +   pthread_t tidA, tidB;
 +
 +   iContador = 0;
 +
 +   pthread_create(&tidA, NULL, teste_thread, NULL);
 +   pthread_create(&tidB, NULL, teste_thread, NULL);
 +
 +   printf("\nEsperando A terminar");
 +   pthread_join(tidA, NULL);
 +   printf("\nEsperando B terminar");
 +   pthread_join(tidB, NULL);
 +
 +   return;
 +}
 +</code>
  
threads_posix.txt · Última modificação: 2023/09/12 16:14 por 127.0.0.1