這是我做的測試例子,考慮到一個線程用于去讀數據庫,一次性插入多條數據到共享數據區,另外搞2個上的線程去讀這個共享數據區,以后打算搞個線程池來處理讀部分。
目下的問題是我想把這個共享數據區做成可變化的動態區,當讀入數據大時,一次讀入全部讀完。當數據量小時,則在規范范圍的空間中運行。
采用vector<mystructData>方式動態變化,比如要刪除超過長度之外的設置,只需要earse就可以了,在線程中每次通過begin,end自動掃描處理中數據部分。
如果把線程部分放到dll中,那么考慮到如何讀取共享數據區,采用導出函數方式,把主線程中的一個函數地址傳入到dll中,然后在這個函數中通過
find_if(a.begin(),a.end(),myfunc)照樣可以處理dll中跑線程的問題,之所以考慮用dll分離各個線程部分,是考慮到業務不同時,每個dll處理掃描共享數據區,發現自己的業務就去處理,不是則不理會,這樣考慮設計可以通過編寫dll方式來擴展不同的業務。
#include "stdafx.h"
#include
<vector>
#include <iostream>
#include
<windows.h>
#include <process.h>
#include
<algorithm>
using namespace std;
struct te
{
int IsGet;
int a1;
int
s1;
char b1[20];
};
bool isget(te t)
{
return t.IsGet ==1;
}
bool getdata(te
t)
{
return t.IsGet==0;
}
vector<te> a;
HANDLE
hMutex;
void myprint(te t)
{
cout<<" ALL
"<< (t.IsGet == 0? "Have": "No ")<<
"("<<t.a1<<")"<<t.s1<<" " << t.b1
<<endl;
}
DWORD WINAPI insertdata( LPVOID lpParam
)
{
vector<te>::iterator p;
int i =
0;
while (1)
{
do{
p =
find_if(a.begin(), a.end(), isget);
if (p!=
a.end())
{
WaitForSingleObject(hMutex,
INFINITE);
i++;
p->IsGet =
0;
p->s1 =
i;
sprintf(p->b1, "%s- %d", "thread_insert" ,
i);
cout<<"
insert("<<p->a1<<") " << p->s1<<" " <<
p->b1 <<endl;
ReleaseMutex(hMutex);
}
//Sleep(1000);
}
while(p !=
a.end());
WaitForSingleObject(hMutex,
INFINITE);
cout<<"---------------------------"<<endl;
for_each(a.begin(),
a.end(),
myprint);
ReleaseMutex(hMutex);
Sleep(11000);
}
return 0;
}
//讀線程,讀完對IsGet標志為1
DWORD WINAPI processdata( LPVOID lpParam
)
{
vector<te>::iterator
p;
while(1)
{
WaitForSingleObject(hMutex,
INFINITE);
p = find_if(a.begin(), a.end(),
getdata);
if (p != a.end())
{
cout<<"("<< (char*)lpParam << ") get ("
<< p->a1<<") " << p->s1 <<" " << p->b1
<<endl;
p->IsGet =
1;
p->s1 = 0;
p->b1[0] =
'\0';
}
ReleaseMutex(hMutex);
Sleep(500);
}
return 0;
}
int main(int argc, char* argv[])
{
HANDLE
hInsertHandle, hProcessHandle1,hProcessHandle2;
DWORD dwThreadId;
te tt1;
for(int i = 0; i <
10;i++)
{
tt1.IsGet =
1;
//可以寫入標志
tt1.a1 = i;
tt1.s1 =
0;
sprintf(tt1.b1,"%d",
i);
a.push_back(tt1);
}
hMutex = CreateMutex(NULL, false, "mutex");
hInsertHandle = CreateThread(
NULL,
0,
insertdata,
NULL,
// argument to thread function
0,
// use default creation flags
&dwThreadId);
hProcessHandle1 = CreateThread(
//讀出線程1
NULL,
0,
processdata,
"proc1"
,
0,
&dwThreadId);
hProcessHandle2 = CreateThread(
NULL,
0,
processdata,
"proc2",
0,
&dwThreadId);
while(1)
{
printf("main thread
...\n");
char c = getchar();
if (c==
'q')
break;
}
return 0;
}