我的程序中有两个线程(Thread1和Thread2),他们都会对同一数据进行修改,为了保证在同一时间内只有一个线程修改数据,我想用互斥量来同步两个线程。但总是出问题(runtime error).
我是这么做的:
1。在主程序中定义了互斥对象HANDLE m_hMutex = CreateMutex(NULL,FALSE,NULL);
其初始状态为未被激活的。
2。在Thread1的SetData(...)和Thread2的UpdateData(...)中我都是这样用互斥量的:
void SetData(...)
{
DWORD dw =::WaitForSingleObject(m_hMutex,INFINITE);
if(dw == WAIT_OBJECT_0)
{
修改数据;
}
BOOL bm = ReleaseMutex(m_hMutex);
ASSERT(bm);
}void UpdateData(...)函数同上。但这样始终没办法解决两个线程的互斥问题。我是不是在使用上有误?
另外,互斥量初始状态为未被激活的,那么什么时候会被激活呢?
我是这么做的:
1。在主程序中定义了互斥对象HANDLE m_hMutex = CreateMutex(NULL,FALSE,NULL);
其初始状态为未被激活的。
2。在Thread1的SetData(...)和Thread2的UpdateData(...)中我都是这样用互斥量的:
void SetData(...)
{
DWORD dw =::WaitForSingleObject(m_hMutex,INFINITE);
if(dw == WAIT_OBJECT_0)
{
修改数据;
}
BOOL bm = ReleaseMutex(m_hMutex);
ASSERT(bm);
}void UpdateData(...)函数同上。但这样始终没办法解决两个线程的互斥问题。我是不是在使用上有误?
另外,互斥量初始状态为未被激活的,那么什么时候会被激活呢?
你怎么释放了啊,应该在主程序里释放啊
InitializeCriticalSection(&CriticalSection);//初始化互斥区
EnterCriticalSection(&CriticalSection);
//读写数据
LeaveCriticalSection(&CriticalSection);
当WaitForSingleObject函数成功返回时,互斥信号处于通知状态,调用ReleaseMutex函数时释放,互斥信号便处于未通知状态,其他线程就可以访问互斥信号
谁能讲讲Mutex的使用方法呢
Thread1就是我的主线程,Thread2运行于Thread1中,所以我不能让Thread1完全挂起,不然Thread2也不能运行了。所以我想在某一点(修改数据时)能够同步就可以了,不知我的想法对吗?
HANDLE m_hMutex = CreateMutex(NULL,FALSE, _T("The only one mutex name"));
另外建议最好判断 m_hMutex 的返回值是否为 ERROR_INVALID_HANDLE
你的思路应该是正确的
HANDLE hMutex; // Create a mutex with no initial owner.hMutex = CreateMutex(
NULL, // no security attributes
FALSE, // initially not owned
"MutexToProtectDatabase"); // name of mutexif (hMutex == NULL)
{
// Check for error.
}
When a thread of this process writes to the database, as in the next example, it first requests ownership of the mutex. If it gets ownership, the thread writes to the database and then releases its ownership.The example uses structured exception-handling syntax to ensure that the thread properly releases the mutex object. The __finally block of code is executed no matter how the __try block terminates (unless the __try block includes a call to the TerminateThread function). This prevents the mutex object from being abandoned inadvertently.BOOL FunctionToWriteToDatabase(HANDLE hMutex)
{
DWORD dwWaitResult; // Request ownership of mutex.
dwWaitResult = WaitForSingleObject(
hMutex, // handle to mutex
5000L); // five-second time-out interval
switch (dwWaitResult)
{
// The thread got mutex ownership.
case WAIT_OBJECT_0:
__try {
// Write to the database.
} __finally {
// Release ownership of the mutex object.
if (! ReleaseMutex(hMutex))
{
// Deal with error.
} break;
} // Cannot get mutex ownership due to time-out.
case WAIT_TIMEOUT:
return FALSE; // Got ownership of the abandoned mutex object.
case WAIT_ABANDONED:
return FALSE;
} return TRUE;
}
DWORD dw =::WaitForSingleObject(m_hMutex,INFINITE);
if(dw == WAIT_OBJECT_0)
{
修改数据;
}
BOOL bm = ReleaseMutex(m_hMutex);
这样应该是没有问题的
我认为我的思路可能有问题,因为Thread1是主线程,其他任何线程都是在主线程中创建的,但现在Thread1要与Thread2互斥,那么当Thread2在获得CPU时间后,Thread1被阻塞会不会影响Thread2的运行?
请大家帮我分析分析!