|
|
实在是搞不定了,,帮帮忙啊~~~多线程访问老出错.
想法很简单就是把线程里面需要执行的同步方法通知给主线程要主线程执行.帮看看
#include <iostream>
#include <vector>
#include <process.h>
#include <windows.h>
using namespace std;
class T1;
typedef struct
{
T1* pT1;
HANDLE signal;
}SyncRec,*PSyncRec;
vector < SyncRec> *pList=NULL;
unsigned _stdcall process(void* param);
CRITICAL_SECTION sec;
HANDLE mainevent;
void addsync(T1 *pt1)
{
SyncRec srec;
srec.pT1=pt1;
srec.signal=CreateEvent(NULL,true,false,NULL);
EnterCriticalSection(&sec);
if(pList==NULL)
{
pList=new vector <PSyncRec>();
pList->push_back(&srec);
}
LeaveCriticalSection(&sec);
SetEvent(mainevent);
WaitForSingleObject(srec.signal,INFINITE);
CloseHandle(srec.signal);
}
class T1
{
public:
HANDLE hand;
unsigned sid;
T1()
{
hand=(HANDLE)_beginthreadex(NULL,0,process,this,0,&sid);
printf("%d create:",hand);
}
void execute()
{
printf("execute\n");
addsync(this);
}
void sync()
{
printf("hello\n");
}
};
unsigned _stdcall process(void* param)
{
T1 *pt1=(T1*)param;
pt1->execute();
delete pt1;
pt1=NULL;
_endthreadex(0);
return 0;
}
void processAnsy()
{
ResetEvent(mainevent);
vector <PSyncRec> *pLocal=NULL;
EnterCriticalSection(&sec);
pLocal=(vector <PSyncRec> *)InterlockedExchange((long*)&pList,(long)pLocal);
if(pLocal!=NULL&&pLocal->size()>0)
{
while(pLocal->size()>0)
{
PSyncRec px=(PSyncRec)pLocal->front();
pLocal->pop_back();
LeaveCriticalSection(&sec);
px->pT1->sync();
EnterCriticalSection(&sec);
SetEvent(px->signal);
}
delete pLocal;
}
LeaveCriticalSection(&sec);
}
void test()
{
for(int i=0;i <2;i++)
{
T1 *pt1=new T1();
}
}
int main()
{
InitializeCriticalSection(&sec);
test();
mainevent=CreateEvent(NULL,true,false,NULL);
while(true)
{
WaitForSingleObject(mainevent,INFINITE);
processAnsy();
}
char str[10];
gets(str);
return 0;
} |
|