- Set the thread information structure body
1 struct Threadinfo 2 {3 int *pstart; 4 int length; 5 int key; 6 int ID; 7 };
- Set array
1 int a[]; 2 time_t ts; 3 int) Time (&ts)); 4 for (int0; i++) 5 {6 ; 7 }
- Initialize the thread structure and start the thread
1 structThreadinfo info[Ten];2 for(inti =0; I <Ten; i++)3 {4Info[i].pstart = A + I *Ten;5Info[i].length =Ten;6Info[i].key =5;7Info[i].id =i;8_beginthread (Find,0, &info[i]);9}
- multithreaded functions
1 voidFindvoid*p)2 {3 structThreadinfo *pinfo = p;//Accept Parameters4printf"thread%d starts \ n", pinfo->ID);5 for(int*PX = pinfo->pstart; PX < Pinfo->pstart + pinfo->length; px++)6 {7 if(*px = = pinfo->key)8 {9printf"thread%d found%d,%d\n", Pinfo->id, PX, *px);TenEnQ (&my1, *px);//Address Queue One } A } -printf"thread%d ends \ n", pinfo->ID); -}
Multi-threaded operation of the incoming struct body.
Full code:
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 8MyQ my1;//queue saves multi-threaded results9 Ten structThreadinfo One { A int*Pstart; - intlength; - intkey; the intID; - }; - - voidFindvoid*p) + { - structThreadinfo *pinfo = p;//Accept Parameters +printf"thread%d starts \ n", pinfo->ID); A for(int*PX = pinfo->pstart; PX < Pinfo->pstart + pinfo->length; px++) at { - if(*px = = pinfo->key) - { -printf"thread%d found%d,%d\n", Pinfo->id, PX, *px); -EnQ (&my1, *px);//Address Queue - } in } -printf"thread%d ends \ n", pinfo->ID); to } + - voidMain () the { *Init (&MY1);//Initialize Queue $ inta[ -];Panax Notoginseng time_t ts; -Srand ((unsignedint) Time (&ts)); the for(inti =0; I < -; i++) + { AA[i] = rand ()%Ten; the } + - $ structThreadinfo info[Ten]; $ for(inti =0; I <Ten; i++) - { -Info[i].pstart = A + I *Ten; theInfo[i].length =Ten; -Info[i].key =5;WuyiInfo[i].id =i; the_beginthread (Find,0, &info[i]); - } WuSleep ( the); - //Eject queue all data About while(!isempty (&my1)) $ { -printf"data from the team:%d\n", GetLast (&my1)); -DeQ (&my1); -Print (&my1); A } + theSystem"Pause"); -}
52. Multi-Threaded lookup data