- 设置线程信息结构体
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 threadInfo info[10]; 2 for (int i = 0; i < 10; i++) 3 { 4 info[i].pstart = a + i * 10; 5 info[i].length = 10; 6 info[i].key = 5; 7 info[i].id = i; 8 _beginthread(find, 0, &info[i]); 9 }
- 多线程函数
1 void find(void *p) 2 { 3 struct threadInfo *pinfo = p;//接受参数 4 printf("线程%d开始\n", pinfo->id); 5 for (int *px = pinfo->pstart; px < pinfo->pstart + pinfo->length; px++) 6 { 7 if (*px == pinfo->key) 8 { 9 printf("线程%d找到%d,%d\n", pinfo->id, px, *px); 10 enQ(&my1, *px);//地址入队 11 } 12 } 13 printf("线程%d结束\n", pinfo->id); 14 }
对传入的结构体进行多线程操作.
完整代码:
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 }