无锁栈实现一例 (四)

2014-11-24 02:00:37 · 作者: · 浏览: 8
th[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)AesThreadFunc, &ad, 0, NULL);
} // for
::WaitForMultipleObjects(knThreadCount, th, TRUE, INFINITE);
}

{
// Test pop.
AutoHRTimer ahr(g_hrtimer, "ACS pop 5000");
for (int i = 0; i < knPopedCount; ++i) {
poped_node = acs_deque_pop(&ad);
delete poped_node;
}
}

{
AutoHRTimer ahr(g_hrtimer, "ACS free 45000");
acs_node_t* cur = ad.head.next;
while (cur != NULL) {
acs_node_t* tmp = cur;
cur = cur->next;
delete tmp;
}
}
}

static DWORD StdThreadFunc(void* arg)
{
StdDeque* deq_list = (StdDeque*)arg;

for (int i = 0; i < knMaxNodeCount; ++i) {
DequeData* dd = new DequeData;
dd->id = "randid_";
dd->id.push_back((i % 10) + '0');
dd->index = i;
EnterCriticalSection(&g_stdcs);
deq_list->push_back(dd);
LeaveCriticalSection(&g_stdcs);
} // for

return 0;
}

static void TestLockedDeque()
{
StdDeque deq_list;
DequeData* poped_dd = NULL;
HANDLE th[knThreadCount];
InitializeCriticalSectionAndSpinCount(&g_stdcs, 2000);

{
AutoHRTimer ahr(g_hrtimer, "STD push 50000");
for (int i = 0; i < knThreadCount; ++i) {
th[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)StdThreadFunc, &deq_list, 0, NULL);
} // for
::WaitForMultipleObjects(knThreadCount, th, TRUE, INFINITE);
}

{
AutoHRTimer ahr(g_hrtimer, "STD pop 5000");
for (int i = 0; i < knPopedCount; ++i) {
poped_dd = deq_list.front();
deq_list.pop_front();
delete poped_dd;
}
}

{
AutoHRTimer ahr(g_hrtimer, "STD free 45000");
StdDeque::iterator iter = deq_list.begin();
while (iter != deq_list.end()) {
DequeData* dd = *iter;
delete dd;
++iter;
}
deq_list.clear();
}

DeleteCriticalSection(&g_stdcs);
}

int main()
{
while (1) {
TestAcsDeque();
TestLockedDeque();
Sleep(3000);
fprintf(stdout, "--------------------------------------\n");
}

getchar();

return 0;
}

#include

#include

#define WIN32_LEAN_AND_MEAN
#include

#include

static const int knThreadCount = 4;
static const int knMaxNodeCount = 50000;
static const int knPopedCount = 5000;

/* ACS node define. */
typedef struct acs_node_t {
std::string id;
int index;
struct acs_node_t* next;
} acs_node_t;

/* ACS deque define. */
typedef struct acs_deque_t {
struct acs_node_t head;
struct acs_node_t* tail;
} acs_deque_t;

typedef struct DequeData {
std::string id;
int index;
} DequeData;

typedef std::deque StdDeque;

CRITICAL_SECTION g_stdcs;

int g_aes_cost_time = 0;
int g_std_cost_time = 0;

class HRTimer {
public:
HRTimer();
~HRTimer() {}

double GetFrequency(void);
void StartTimer(void);
double StopTimer(void);

private:
LARGE_INTEGER start_;
LARGE_INTEGER stop_;
double frequency_;
};

HRTimer::HRTimer()
: start_(),
stop_(),
frequency_(0.f)
{
frequency_ = this->GetFrequency();
}

double HRTimer::GetFrequency(void)
{
LARGE_INTEGER proc_freq;
if (!::QueryPerformanceFrequency(&proc_freq))
return 0.f;
return proc_freq.QuadPart;
}

void HRTimer::StartTime