windowsxp-vc6环境下双线程临界区实现:
#include <windows.h>
#include <stdio.h>
#include <process.h>
int threadflag[2]; //线程标志
int door; //进入标志
long crtsec = 0; //冲突域
HANDLE lock; //信号量
CRITICAL_SECTION cs;
int allnum = 100000000;
int testnum;
void indoor(int threadid)
{
//记录线程标志
int other = 1 - threadid;
threadflag[threadid] = 1;
door = threadid;
//用户态直接判断是否可以进入
if(threadflag[other]==1&&door!=other)
//判断是否优先于其他线程
if(InterlockedDecrement(&crtsec) < 0)
//等待信号
WaitForSingleObject(lock, INFINITE);
{
int other = 1 - threadid;
//用户态直接判断有无其他线程
if(threadflag[other]==1)
//判断是否优先于其他线程
if(InterlockedIncrement(&crtsec) <= 0)
//唤醒线程
ReleaseSemaphore(lock, 1, NULL);
//释放线程标志
threadflag[threadid] = 0;
{
int temp;
while(1)
{
indoor((int)p);
//EnterCriticalSection(&cs);
if(allnum>0)
{
temp = allnum;
testnum++;
allnum = temp - 1;
outdoor((int)p);
//LeaveCriticalSection(&cs);
}
else
{
outdoor((int)p);
//LeaveCriticalSection(&cs);
break;
}
}
return 1;
{
//long tt = 10;
//InterlockedIncrement(&tt);
HANDLE thread[2];
//lock = CreateEvent(NULL, FALSE, FALSE, NULL);
lock = CreateSemaphore(NULL, 0, 1, NULL);
InitializeCriticalSection(&cs);
thread[0] = CreateThread(NULL, 0, threadfunc, (void *)0, 0, NULL);
thread[1] = CreateThread(NULL, 0, threadfunc, (void *)1, 0, NULL);
WaitForMultipleObjects(2, thread, TRUE, INFINITE);
printf("the num is %d/n", testnum);
the num is 100880401
Press any key to continue
不知道问题到底出在什么地方,多线程方面的高手请帮忙分析下,
至于几种同步方式的比较和测试和结果请看另一篇<线程同步的几种方法效率比较>