1. 程式人生 > >62.多線程多文件檢索,每個線程檢索一個文件,用於內存不夠的情況下

62.多線程多文件檢索,每個線程檢索一個文件,用於內存不夠的情況下

tdi 保存 dst 針對 ces inf 2個 printf fclose

  1 #define _CRT_SECURE_NO_WARNINGS
  2 #include<stdio.h>
  3 #include<stdlib.h>
  4 #include <string.h>
  5 #include <memory.h>
  6 #include <process.h>
  7 #include <Windows.h>
  8 //多線程多文件,實現線程的調度
  9 //釋放內存
 10 //內存不夠的情況,排隊完成任務
 11 
 12 //創建多線程結構體
 13 struct infos
 14
{ 15 //路徑 16 char path[256]; 17 //線程id 18 int id; 19 //把文件的內容載入 20 char **g_pp; 21 //文件的長度 22 int length; 23 //要查詢的數據 24 char findstr[100]; 25 }myinfo[22] = {0};//22個結構體保存了22個文件的信息 26 HANDLE inithd[22] = {0};//22個初始化線程地址 27 HANDLE findhd[22] = { 0 };//22個查找線程地址 28 29
//根據路徑初始化線程地址,把數據寫入到infos結構體中 30 void runthreadinit(void *p) 31 { 32 struct infos *pinfo = p; 33 FILE *pf = fopen(pinfo->path, "r"); 34 if (pf!=NULL) 35 { 36 //測試多少行 37 int i = 0; 38 while (!feof(pf)) 39 { 40 char str[256] = { 0 }; 41
fgets(str, 256, pf);//讀取 42 i++; 43 } 44 //i記錄行數 45 rewind(pf);//回到開頭 fseek(pf,0,SEEK_SET); 46 pinfo->g_pp = calloc(i, sizeof(char*));//分配內存初始化 47 pinfo->length = i;//記錄長度 48 49 //讀取並把數據拷貝到g_pp[i]中 50 for (int j = 0; j < i;j++) 51 { 52 char str[256] = { 0 }; 53 //讀取 54 fgets(str, 256, pf); 55 //獲取長度 56 int length = strlen(str); 57 //分配內存 58 pinfo->g_pp[j] = calloc(length + 1, sizeof(char)); 59 //拷貝到**g_pp中 60 if (pinfo->g_pp[j]!=NULL) 61 { 62 strcpy(pinfo->g_pp[j], str); 63 } 64 } 65 } 66 //關閉文件 67 fclose(pf); 68 printf("線程%d init over\n", pinfo->id); 69 } 70 71 //調用線程函數 72 void runthreadsearch(void *p) 73 { 74 //指針類型轉換 75 struct infos *pinfo = p; 76 //每個線程都進行相應的檢索 77 for (int i = 0; i < pinfo->length;i++) 78 { 79 if (pinfo->g_pp[i]!=NULL) 80 { 81 char *px = strstr(pinfo->g_pp[i], pinfo->findstr); 82 if (px!=NULL) 83 { 84 printf("\n%s", pinfo->g_pp[i]); 85 } 86 } 87 } 88 89 printf("線程%d find over\n", pinfo->id); 90 } 91 92 //釋放內存 93 void freeall(struct infos *pinfo) 94 { 95 printf("freeall start"); 96 //釋放指針數組每一個指針對於的內存 97 for (int i = 0; i < pinfo->length;i++) 98 { 99 free(pinfo->g_pp[i]); 100 } 101 free(pinfo->g_pp);//釋放g_pp 102 103 printf("freeall end;"); 104 105 } 106 107 void main() 108 { 109 //給線程結構體初始化地址和要查詢的字符串 110 for (int i = 0; i < 15;i++) 111 { 112 myinfo[i].id = i+1; 113 sprintf(myinfo[i].path, "dangdangwang%d.txt", i + 1); 114 strcpy(myinfo[i].findstr, "小王"); 115 } 116 117 //根據地址初始化結構體 118 for (int i = 0; i < 15;i++) 119 { 120 inithd[i] = _beginthread(runthreadinit, 0, &myinfo[i]); 121 } 122 //等待 123 WaitForMultipleObjects(15, inithd, TRUE, INFINITE); 124 system("pause"); 125 126 //執行查找線程 127 for (int i = 0; i < 15;i++) 128 { 129 findhd[i] = _beginthread(runthreadsearch, 0, &myinfo[i]); 130 } 131 //等待 132 WaitForMultipleObjects(15, findhd, TRUE, INFINITE); 133 system("pause"); 134 135 //釋放所有內存 136 printf("開始釋放"); 137 for (int i = 0; i < 15;i++) 138 { 139 freeall(&myinfo[i]); 140 } 141 printf("結束釋放"); 142 143 system("pause"); 144 }

62.多線程多文件檢索,每個線程檢索一個文件,用於內存不夠的情況下