global.h
#include <queue>
#ifndef LPVOID
#define void* LPVOID
#endif
class global
{
public:
#ifdef _MSC_VER
HANDLE m_hBufThread;
HANDLE m_hBufWeakUpSignal;
CRITICAL_SECTION m_cs;
#else
pthread_t m_hBufThread;
pthread_cond_t m_hBufWeakUpSignal;
pthread_mutex_t m_cs;
#endif
queue<testStruct>* m_hqueue;
}
global.cpp
#include "stdafx.h"
#include "JtGlobal.h"
#if _MSC_VER
void jtProcessGlobalThread(LPVOID lpParam)
#else
void *jtProcessGlobalThread(LPVOID lpParam)
#endif
{
JtGlobal* pGlobal = (JtGlobal*)lpParam;
while (pGlobal->m_hBufThread)
{
JtEnterCriticalSection(&pGlobal->m_cs);
if (pGlobal->m_hqueue->empty())
{
#if _MSC_VER
JtLeaveCriticalSection(&pGlobal->m_cs);
WaitForSingleObject(pGlobal->m_hBufWeakUpSignal, INFINITE);
ResetEvent(pGlobal->m_hBufWeakUpSignal);
continue;
#else
pthread_cond_wait(&pGlobal->m_hBufWeakUpSignal, &pGlobal->m_cs);
#endif
}
JtLeaveCriticalSection(&pGlobal->m_cs);
}
}
global::global()
{
#if _MSC_VER
InitializeCriticalSection(&m_cs);//初始化
m_hBufWeakUpSignal = CreateEvent(NULL, TRUE, TRUE, NULL);
m_hBufThread = (HANDLE)_beginthread(jtProcessGlobalThread, 0, this);
#else
pthread_mutex_init(&m_cs, NULL);//临界区
pthread_cond_init(&m_hBufWeakUpSignal, NULL); //标志
pthread_create(&m_hBufThread, NULL, jtProcessGlobalThread, this); //创建线程
#endif
m_hqueue = new queue<testStruct>;
}
global::~global()
{
#if _MSC_VER
if (m_hBufThread)
{
if (WaitForSingleObject(m_hBufThread, 100) == WAIT_TIMEOUT)
{
TerminateThread(m_hBufThread, 0);
}
m_hBufThread = NULL;
}
CloseHandle(m_hBufWeakUpSignal);
DeleteCriticalSection(&m_cs);
#else
pthread_join(m_hBufThread, NULL);
#endif
}