Advertisement
Guest User

Untitled

a guest
Sep 5th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.45 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <winsock.h>
  4. #include <string.h>
  5. #include <malloc.h>
  6.  
  7. //Tamanho da fila de impressao
  8. #define TAMANHO_FILA 5//Limitar impede o consumo de memoria pelo thread2
  9.  
  10. /* DECLARAÇÕES GLOBAIS */
  11. //~~thread's
  12. void *runn_thr1(void *);//thread 1 (gerenciador de fila)
  13. void *runn_thr2(void *);//thread 2 (impressor)
  14.  
  15. void init_threads();//inicia threads
  16.  
  17. pthread_mutex_t vblock_gfila;//Variavel de bloqueio - thread 1
  18. pthread_mutex_t vblock_imp;//Variavel de bloqueio - thread 2
  19.  
  20. pthread_t thr1,**thr2;//variaveis do thread
  21.  
  22. //~~menu
  23. int menu();
  24.  
  25. //~~variaveis globais - uso ativo de thread
  26. bool add_fila = false; //sinalizador - adicionar arquivo a fila
  27. bool imp_arquivo = false;//sinalizador - imprimir arquivo na fila
  28.  
  29. int fila_count = 0;//Armazena quantidade de arquivos na fila
  30. int thr2id = 0;
  31.  
  32. //Arquivo a ser impresso
  33. struct Arquivo
  34. {
  35. //Dados comuns de um arquivo a ser impresso
  36. char *nome;
  37.  
  38. //Limpar variaveis
  39. void clear(){
  40. nome = NULL;
  41. };
  42. //Altera nome do arquivo - ja aloca de acordo com a string enviada
  43. void set(const char *str){
  44. nome = (char *)malloc(sizeof(char *)*strlen(str));
  45. strcpy(nome, str);
  46. };
  47. };
  48. //Arquivo temporario - usado para passar dados, do processo principal para o thread 1, depois para o thread 2
  49. Arquivo file_temp;
  50. Arquivo **fila_thr2;//usar esse objeto para armazenar as informacões dos 'arquivos' da fila
  51.  
  52. /* FIM DECLARAÇÕES GLOBAIS */
  53.  
  54.  
  55.  
  56.  
  57.  
  58. int main(){
  59. init_threads();//inicia threads
  60. menu();//menu
  61.  
  62. return 0;
  63. }
  64. //Mostra menu na tela, executa funções do menu
  65. int menu(){
  66. int r = 0,l = 1;
  67.  
  68. //Aloca vetor da fila e thread2
  69. fila_thr2 = (Arquivo **)malloc(sizeof(Arquivo *)*TAMANHO_FILA);
  70. thr2 = (pthread_t **)malloc(sizeof(pthread_t *)*TAMANHO_FILA);
  71. for(int i = 0; i < TAMANHO_FILA; i++){
  72. fila_thr2[i] = NULL;
  73. thr2[i] = NULL;
  74. }
  75.  
  76. while(l){
  77. //Limpa dados de entrada
  78. fflush(stdin);
  79.  
  80. //Texto do menu
  81. printf(" == MENU == \n");
  82. printf("1 - Imprimir arquivos em fila \n");
  83. printf("2 - Adicionar arquivo a fila de impressao \n");
  84. printf("3 - Ver fila de impressao\n");
  85. printf("0 - Sair \n");
  86. printf("\n>");
  87. scanf("%d",&r);
  88.  
  89. if(r == 0) break;
  90.  
  91.  
  92. switch(r){
  93. case 1://Imprimir arquivos da fila
  94. imp_arquivo = true;//Sinaliza impressao
  95. break;
  96. case 2://Adicionar arquivo
  97. {
  98. //Fila cheia
  99. if(fila_count >= TAMANHO_FILA){
  100. printf("Fila cheia! Tente mais tarde.\n");
  101. break;
  102. }
  103. //Alocando memoria - struct Arquivo
  104. file_temp.nome = (char *)malloc(sizeof(char *)*128);
  105.  
  106. //Questionario
  107. printf("Digite o nome do arquivo(128):");
  108. scanf("%s",file_temp.nome);
  109.  
  110. //Enviar para thread 1
  111. add_fila = true;
  112.  
  113. }
  114. break;
  115. case 3://Mostrar Fila
  116. {
  117. if(fila_count <= 0){
  118. printf("Fila vazia! Tente mais tarde.\n");
  119. break;
  120. }
  121. int i;
  122. for(i = 0; i < TAMANHO_FILA; i++){
  123. if(fila_thr2[i] != NULL){
  124. printf("[%d] - %s\n",i,fila_thr2[i]->nome);
  125. }
  126. }
  127. }
  128. break;
  129. case 0:
  130. l = 0;
  131. break;
  132. }
  133. }
  134. }
  135. /*thread para efeutar compra, verificar saldo, etc*/
  136. void *runn_thr1(void *){
  137. Arquivo thr_tmp; // Armazena arquivo temporario, mesmo que mudo o global(file_temp)
  138.  
  139. while(1){//Loop eterno até que seja interrompido ou um arquivo esteja para ser adicionado
  140.  
  141. if(add_fila){//Solicitação para adicionar na fila
  142. add_fila = false;
  143. pthread_mutex_unlock(&vblock_gfila);//Impede dupla solicitação
  144.  
  145. //Copia dados do arquivo para o struct thr_tmp do thread1
  146. thr_tmp.set(file_temp.nome);
  147. file_temp.clear();
  148.  
  149. Sleep(5000);//Delay de solicitação - so assim é possivel perceber o uso do pthread_mutex_unblock.
  150. thr2id = 0;//slot thread
  151.  
  152. //Encontra um slot vazio para colocar o arquivo na fila
  153. for(int i = 0; i < TAMANHO_FILA; i++){
  154. if(fila_thr2[i] == NULL){
  155. printf("Slot %d livre.\n",i);
  156.  
  157. //Aloca vetores - Arquivo * e pthread_t
  158. fila_thr2[i] = (Arquivo *)malloc(sizeof(Arquivo *));
  159. thr2[i] = (pthread_t *)malloc(sizeof(pthread_t *));
  160.  
  161. thr2id = i;
  162. //Adiciona nome do arquivo na estrutura da fila
  163. fila_thr2[i]->set(thr_tmp.nome);
  164. printf("Arquivo %s adicionado a fila!\n",fila_thr2[i]->nome);
  165. //Cria thread 2
  166. pthread_create(thr2[i],NULL,runn_thr2,NULL);
  167. //Aumenta contagem
  168. fila_count++;
  169. break;
  170. }
  171. }
  172. //Valor se encontra 0 pois não foi modificado acima
  173. if(thr2id == 0){
  174. printf("Nao foi possivel adicionar arquivo %s a fila.\n",thr_tmp.nome);
  175. }
  176. pthread_mutex_unlock(&vblock_gfila);//Desbloqueia variavel para outra soliciatação de compra
  177. }
  178. }
  179. }
  180.  
  181. //Thread que imprimi arquivos
  182. void *runn_thr2(void *){
  183. int id = thr2id;//Slot do thread
  184. thr2id = -1;
  185.  
  186. while(1){
  187. //Imprimir arquivos - so quando receber o sinal do usuario
  188. if(imp_arquivo){
  189. while(pthread_mutex_unlock(&vblock_imp) < 1){}//Impede dupla impressao - bloqueia variavel ou espera desbloquear
  190.  
  191. printf("Arquivo %s imprimido!\n",fila_thr2[id]->nome);//Output
  192. fila_thr2[id] = NULL;//Esvazia slot da fila
  193. fila_count--;//Aumenta contagem
  194. pthread_mutex_unlock(&vblock_imp);//Impede dupla impressao - bloqueia variavel ou espera desbloquear
  195. break;
  196. }
  197. }
  198. }
  199. //Inicia thread 1
  200. void init_threads(){
  201. pthread_create(&thr1,NULL,runn_thr1,NULL);//Cria thread 1
  202. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement