`
frenchmay
  • 浏览: 229137 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

基于windows线程的并行线性查找

阅读更多
#include <Windows.h>
#include <process.h>
#include <stdio.h>
#include <time.h>

typedef struct{
	int * A;
	int num;
	int key;
	int threadID;
} sParam;

bool Done = FALSE;

#define NUM_THREADS 4

void linearSearch(int * A, int s, int e, int key, DWORD *position)
{
	int i;
	for (i = s; i < e; i++)
	{
		if (Done)
		{
			return;
		}

		if (A[i] == key)
		{
			*position = i;
			Done = TRUE;
			break;
		}
		Sleep(1);
	}
	return;
}

unsigned __stdcall pSearch(LPVOID pAvg){
	DWORD pos = -1;
	if (NULL != pAvg)
	{
		sParam * inArg = (sParam*)pAvg;
		int *A = inArg->A;
		int N = inArg->num;
		int key = inArg->key;
		int tNum = inArg->threadID;

		int start, end;

		start = ((float)N/NUM_THREADS) * tNum;
		end = ((float)N/NUM_THREADS) * (tNum + 1);
		if (tNum == (NUM_THREADS - 1))
		{
			end = N;
		}
		linearSearch(A, start, end, key, &pos);
		delete pAvg;
		pAvg = NULL;
	}
	ExitThread(pos);
}

#define  NUM_KEYS 100000

int main(int argc, char * argv[])
{
	int i, t,sKey = NUM_KEYS - 1, * positon = new int;

	time_t begin;
	time_t end;

	begin = time(NULL);

	HANDLE tHandles[NUM_THREADS];

	int * p = (int*)malloc(sizeof(int)*NUM_KEYS);

	for (t = 0; t < NUM_KEYS; t++)
	{
		*(p + t) = t ;
	}

	for (i = 0; i < NUM_THREADS; i++)
	{
		sParam * pAvg = new sParam;
		pAvg->A = p;

		pAvg->num = NUM_KEYS;
		pAvg->key = sKey;
		pAvg->threadID = i;
		tHandles[i] = (HANDLE)_beginthreadex(NULL, 0, pSearch, (LPVOID)pAvg, 0, NULL);
	}

	WaitForMultipleObjects(NUM_THREADS, tHandles, TRUE, INFINITE);

	for(i = 0; i < NUM_THREADS; i++){
		GetExitCodeThread(tHandles[i], (LPDWORD)positon);
		if (*positon != -1)
		{
			printf("key = %d found at index %d\n", sKey, *positon);
			break;
		}
	}

	end = time(NULL);

	printf("cost = %d\r\n", (end - begin));

	return 0;
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics