Mutex的问题,HANDLE不能用指针传入
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
unsigned int i = 0;
int y = 0;
void mutex_lock(HANDLE *this)
{
char buf[32] = {0};
sprintf(buf, "mutex_%.8X", y++);
*this = CreateMutex(NULL, TRUE, buf);
printf("mutex_lock(%d, %s) = %d\r\n", *this, buf, GetLastError());
WaitForSingleObject(*this, INFINITE);
}
void mutex_unlock(HANDLE *this)
{
ReleaseMutex(*this);
printf("mutex_unlock(%d, %ld)\r\n", *this, GetLastError());//这里出错了,都是183L,即ERROR_ALREADY_EXISTS
CloseHandle(*this);
printf("mutex_unlock(%d, %ld)\r\n", *this, GetLastError());
*this = NULL;
printf("mutex_unlock(%d, %ld)\r\n", *this, GetLastError());
}
void xtracer(const char *fmt, ...)
{
FILE *fp = fopen("tracer.txt", "a");
va_list app;
va_start(app, fmt);
vfprintf(fp, fmt, app);
va_end(app);
fclose(fp);
}
void ttt(int x)
{
HANDLE mutex = NULL;
mutex_lock(&mutex);
while (i<0xFF)
xtracer("%d, hello world, %u\r\n", x, i++);
mutex_unlock(&mutex);
}
int main(int argc, char *argv[])
{
HANDLE handle[2] = {0};
handle[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ttt, (void *)1, 0, NULL);
handle[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ttt, (void *)2, 0, NULL);
WaitForSingleObject(handle[0], INFINITE);
WaitForSingleObject(handle[1], INFINITE);
return(0);
}
控制台输出就是:
mutex_lock(2008, mutex_00000000) = 0
mutex_lock(2004, mutex_00000001) = 0
mutex_unlock(2004, 183)
mutex_unlock(2004, 183)
mutex_unlock(0, 183)
mutex_unlock(2008, 183)
mutex_unlock(2008, 183)
mutex_unlock(0, 183)
看得出ReleaseMutex和CloseHandle都失效了,为什么呢?
如果把HANDLE做为一个结构的成员,那么用结构指针在mutex_lock和mutex_unlock之间赋值和传值就不会有这个错误
HANDLE原型是void *,是不是用void **在函数之间赋值和传值是不正确的操作?