日期:2014-05-17  浏览次数:20753 次

基于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;
}
?