Buscar

pthread03

Esta é uma pré-visualização de arquivo. Entre para ver o arquivo original

/*Faça um programa em pthread que crie 10 threads e imprima na tela a ordem de execução de 
cada thread com um id representando a ordem de criação.*/
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 10
//Variável global
typedef struct{
	int id;
} thread_arg;
/* Forma alternativa de criação do struct
struct thread_arg{
	int id;
}
struct thread_arg arg;
*/
//Função que representa a thread
void* minha_thread(void* arg){
	thread_arg *a = (thread_arg*)arg;
	printf("Olá, eu sou a thread %d\n", a->id);
	
	//Finaliza a thread
	pthread_exit((void*)NULL);
}
int main(){
	int i;
	pthread_t tids[NUM_THREADS]; //id das threads		
	thread_arg args[NUM_THREADS];	
	
	//Criando as threads
	for(i = 0; i < NUM_THREADS; i++){
		args[i].id = i;		
		pthread_create(&tids[i], (void*)NULL, minha_thread, (void*)&args[i]);
	}
	//Juntando as threads
	for(i = 0; i < NUM_THREADS; i++){
		pthread_join(tids[i], (void*)NULL);
	}
	printf("Fim do programa\n");
	
	pthread_exit((void*)NULL);
	return 0;
}

Teste o Premium para desbloquear

Aproveite todos os benefícios por 3 dias sem pagar! 😉
Já tem cadastro?

Outros materiais