vc多线程数据同步

来源:互联网 发布:java微信退款接口demo 编辑:程序博客网 时间:2024/05/22 01:51
#include <list>
#include <process.h>
#include <Windows.h>
#include <Winbase.h>


using namespace std;


struct THREAD_DATA
{
int data;
char *imageData;
unsigned int imageSize;
};
struct THREAD_PARAM
{
int index;


};


unsigned int threadId[3];
HANDLE handle[3];
CRITICAL_SECTION m_cs;
list<THREAD_DATA *> g_list;
HANDLE  m_hThreadEvent; //事件


HANDLE g_hSemaphoreBufferEmpty, g_hSemaphoreBufferFull;




void SetDataFun()
{
//等待有空的缓冲区出现  
WaitForSingleObject(g_hSemaphoreBufferEmpty, INFINITE);


THREAD_DATA* pData = new THREAD_DATA;
static int nCount = 0;
pData->data = nCount++;
int nBuff = rand() % 8192;
pData->imageData = new char[nBuff];
pData->imageSize = nBuff;
printf("*********Set data %d \n", pData->data);
EnterCriticalSection(&m_cs);
g_list.push_back(pData);
LeaveCriticalSection(&m_cs);
//通知消费者有新数据了  
ReleaseSemaphore(g_hSemaphoreBufferFull, 1, NULL);
}
unsigned int __stdcall SetDataProc(void* pParam)
{
while (true)
{
SetDataFun();
Sleep(100);
}


}
void GetDataFun()
{
//等待非空的缓冲区出现  
WaitForSingleObject(g_hSemaphoreBufferFull, INFINITE);
EnterCriticalSection(&m_cs);
bool bEmpty = g_list.empty();
LeaveCriticalSection(&m_cs);
if (!bEmpty)
{
THREAD_DATA* pData = NULL;
EnterCriticalSection(&m_cs);
pData = g_list.front();
g_list.pop_front();
LeaveCriticalSection(&m_cs);
printf("---------------------Get data %d data Size %d\n", pData->data,pData->imageSize);
if (pData != NULL)
{

delete[] pData->imageData;
delete pData;
printf("delete data \n");
}


}
ReleaseSemaphore(g_hSemaphoreBufferEmpty, 1, NULL);
//递增信号量的当前资源计数
}
unsigned int __stdcall GetDataProc(void* pParam)
{
THREAD_PARAM *pParam2 = (THREAD_PARAM *)pParam;
SetEvent(m_hThreadEvent);
printf("index %d current thread id %d\n", pParam2->index, GetCurrentThreadId());
DWORD dwStart2 = GetTickCount();
while (true)
{
if (GetTickCount() - dwStart2 >= 10)
{
GetDataFun();
dwStart2 = GetTickCount();
}
Sleep(1);
}
}


int main()
{
InitializeCriticalSection(&m_cs);


g_hSemaphoreBufferEmpty = CreateSemaphore(NULL, 3, 3, NULL);
g_hSemaphoreBufferFull = CreateSemaphore(NULL, 0, 3, NULL);
//初始化事件和关键段 自动置位,初始无触发的匿名事件  
m_hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
for (int i = 0; i < 10; i++)
HANDLE handleSet = (HANDLE)_beginthreadex(NULL, 0, SetDataProc, 0, 0, 0);


for (int i = 0; i < 3; i++)
{
THREAD_PARAM *pParam = new THREAD_PARAM;
pParam->index = i;
handle[i] = (HANDLE)_beginthreadex(NULL, 0, GetDataProc, (LPVOID)pParam, 0, &threadId[i]);
WaitForSingleObject(m_hThreadEvent, INFINITE); //等待事件被触发
}


getchar();
    return 0;
}
原创粉丝点击