多线程并行检索

来源:互联网 发布:电视点播软件哪个好 编辑:程序博客网 时间:2024/06/07 00:59

有时候查找的时候数据量很大的时候,可以开几个线程一起查找,这样就可以加快查找的速度,用一个简单的例子进行说明。

/************************************************************************//* 并行检索                                                                     *//************************************************************************/#include <windows.h>#include <process.h>#include <iostream>using namespace std;int isfind = 0 ;//0代表没有找到,1代表找到int *pfind = NULL ;//为null没有找到,否则为地址struct infostruct{    int *pstart ;//起始地址    int length ;//长度    int findnum ;//要寻找的数字    int id ;//线程编号};/*unsigned int WINAPI fun(void *p)*/void fun(void *p){    struct infostruct *info = (struct infostruct*)p ;    cout<<"线程"<<info->id<<"开始查找!"<<endl ;    for (int *px = info->pstart ; px < info->pstart + info->length ; px++)    {        if (isfind == 1)        {            cout<<"线程"<<info->id<<"结束查找,其他线程已找到"<<endl ;            _endthread() ;        }        if (*px == info->findnum) //判断是否相等        {            pfind = px ;            isfind = 1 ;//设置标识符找到            cout<<"线程"<<info->id<<"找到"<<*px<<endl ;            _endthread() ;//退出        }    }    cout<<"线程"<<info->id<<"没有找到"<<endl ;}void main(){    int data[1000] = {0} ;    for (int i = 999; i >= 0 ; i--)    {        data[i] =i ;    }    struct infostruct inf[10] ;    for(int i = 0 ; i< 10 ; i++)    {        inf[i].pstart = data + i * 100 ;        inf[i].length = 100 ;        inf[i].findnum = 767 ;        inf[i].id = i ;        //        _beginthreadex(NULL , 0 , fun , &inf[i] , 0 , NULL) ;        _beginthread(fun , 0 , &inf[i]) ;    }    system("pause") ;}

程序运行截图:
这里写图片描述

0 0
原创粉丝点击