52.多線程查找數據
阿新 • • 發佈:2018-02-03
signed 數據 初始 use init sig nbsp time_t struct
- 設置線程信息結構體
1 struct threadInfo 2 { 3 int *pstart; 4 int length; 5 int key; 6 int id; 7 };
- 設置數組
1 int a[100]; 2 time_t ts; 3 srand((unsigned int)time(&ts)); 4 for (int i = 0; i < 100; i++) 5 { 6 a[i] = rand() % 10; 7 }
- 初始化線程結構體並開始線程
1 struct
- 多線程函數
1 void find(void *p) 2 { 3 struct threadInfo *pinfo = p;//
對傳入的結構體進行多線程操作.
完整代碼:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 #include <process.h> 5 #include <windows.h> 6 #include "queue.h" 7 8 myQ my1;//隊列保存多線程的結果 9 10 struct threadInfo 11 { 12 int *pstart; 13 int length; 14 int key; 15 int id; 16 }; 17 18 void find(void *p) 19 { 20 struct threadInfo *pinfo = p;//接受參數 21 printf("線程%d開始\n", pinfo->id); 22 for (int *px = pinfo->pstart; px < pinfo->pstart + pinfo->length; px++) 23 { 24 if (*px == pinfo->key) 25 { 26 printf("線程%d找到%d,%d\n", pinfo->id, px, *px); 27 enQ(&my1, *px);//地址入隊 28 } 29 } 30 printf("線程%d結束\n", pinfo->id); 31 } 32 33 void main() 34 { 35 init(&my1);//初始化隊列 36 int a[100]; 37 time_t ts; 38 srand((unsigned int)time(&ts)); 39 for (int i = 0; i < 100; i++) 40 { 41 a[i] = rand() % 10; 42 } 43 44 45 struct threadInfo info[10]; 46 for (int i = 0; i < 10; i++) 47 { 48 info[i].pstart = a + i * 10; 49 info[i].length = 10; 50 info[i].key = 5; 51 info[i].id = i; 52 _beginthread(find, 0, &info[i]); 53 } 54 Sleep(3000); 55 //彈出隊列所有數據 56 while (!isempty(&my1)) 57 { 58 printf("出隊的數據:%d\n", getlast(&my1)); 59 deQ(&my1); 60 print(&my1); 61 } 62 63 system("pause"); 64 }
52.多線程查找數據