游戏开发论坛

 找回密码
 立即注册
搜索
查看: 1210|回复: 0

实在是搞不定了,,帮帮忙啊~~~多线程访问老阻塞

[复制链接]

7

主题

17

帖子

28

积分

注册会员

Rank: 2

积分
28
发表于 2008-3-31 19:39:00 | 显示全部楼层 |阅读模式
实在是搞不定了,,帮帮忙啊~~~多线程访问老出错.

想法很简单就是把线程里面需要执行的同步方法通知给主线程要主线程执行.帮看看
#include  <iostream>
#include  <vector>
#include  <process.h>
#include  <windows.h>
using namespace std;
class T1;
typedef struct
{
T1* pT1;
HANDLE signal;
}SyncRec,*PSyncRec;

vector &ltSyncRec> *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;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2025-12-20 17:25

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表