Mutual exclusion and synchronization of threads (3) - Windows mutex

What is mutex lock / mutex?

In programming, the concept of a mutex object is to ensure the integrity of the shared data operations. Each object corresponds to a marker can be called "mutual exclusion lock", this tag is used to ensure that at any one time, only one thread to access the object; selected Baidu Encyclopedia - mutex .

That only one thread to access the mutex, other threads if requested occupy the mutex, the lock request thread is suspended. Until the lock owner releases the mutex, CPU scheduling request to lock the thread owns the mutex, the thread is awakened.


Windows-related function of the mutex is as follows:

  • CreateCreateMutex (LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCWSTR lpName); // Create a mutex
  • The WaitForSingleObject (HANDLE hHandle, dwMilliseconds DWORD); // wait request occupies the mutex
  • ReleaseMutex (HANDLE hMutex); // release the mutex

  1. CreateCreateMutex function; represents the creation of a mutex,
  • Parameters lpMutexAttributes : express security properties, usually set to nullptr indicates the default security attributes.
  • Parameters bInitialOwner : Indicates whether immediately after owning the mutex is created, TRUE represents that it has immediately; FALSE said they did not have immediately.
  • Parameters lpName : indicates the name mutex. You can set the name mutex, or by name shared among different threads; if you do not set clear proof can be set to nullptr .
  • Return value: the successful return mutex handle. Failure to return nullptr .
  1. WaitForSingleObject function; represents occupies the mutex wait request:
  • Parameters hHandle : handle. This function can be used to not only request mutex, it can also be used, such as waiting for the end of the thread, the process; waiting for the semaphore, mutex possession, and wait for the signal.
  • Parameters dwMilliseconds : indicates the number of milliseconds. Set to INFINITE represented wait indefinitely.
  • return value:
return value Explanation
WAIT_FAILED It represents a function WaitForSingleObject call fails, you can function GetLastError () to get the error code
WAIT_OBJECT_0 Wait for success to set target
WAIT_TIMEOUT It represents waiting for a timeout
WAIT_ABANDONED If the object Mutex, represents a thread holds Mutex object has ended, but did not release the mutex; this time the object is abandoned Mutex state. The behavior is unknown, is not recommended
  1. ReleaseMutex function, shows the release mutex.
  • Parameters hMutex mutex handle

The following is a simple example of the use of mutex, also uses the CThread :
Header:

class WinMutexThread : public CThread
{
public:
	void run(void) override;

	// 初始化Mutex,用于创建互斥锁
	static void initMutex(void);

private:
	// 互斥锁
	static HANDLE m_mutexHandle;
};

Source File:

#include <iostream>

HANDLE WinMutexThread::m_mutexHandle = nullptr;
int number = 0;

void WinMutexThread::run(void)
{
	while (1)
	{
		if (::WaitForSingleObject(m_mutexHandle, INFINITE) == WAIT_OBJECT_0)
		{
			std::cout << "Current Thread: " << ::GetCurrentThreadId() \
			          << ", Value: " << number++ << std::endl;

			::ReleaseMutex(m_mutexHandle);
		}

		Sleep(1000);
	}
}

void WinMutexThread::initMutex(void)
{
	m_mutexHandle = ::CreateMutex(nullptr, FALSE, nullptr);
}

In the run () function, we simply request mutex, the thread ID and print and make the global variable is incremented by one

transfer

int main(int argc, char** argv)
{
	// 创建互斥锁
	WinMutexThread::initMutex();

	// 创建三个线程
	WinMutexThread thread1;
	WinMutexThread thread2;
	WinMutexThread thread3;
	// 开启线程
	thread1.start();
	thread2.start();
	thread3.start();
	// 等待
	thread1.wait();
	thread2.wait();
	thread3.wait();

	system("pause");
	return 0;
}

运行结果如下:
Current Thread: 12632, Value: 0
Current Thread: 13096, Value: 1
Current Thread: 18652, Value: 2
Current Thread: 12632, Value: 3
Current Thread: 13096, Value: 4
Current Thread: 18652, Value: 5
Current Thread: 12632, Value: 6
Current Thread: 13096, Value: 7
Current Thread: 18652, Value: 8
Current Thread: 12632, Value: 9
Current Thread: 13096, Value: 10
Current Thread: 18652, Value: 11


Author: douzhq
personal blog homepage: not fly a paper airplane
article synchronization page (now complete code) mutually exclusive threads and synchronization (3) - Windows mutex

发布了90 篇原创文章 · 获赞 81 · 访问量 5万+

Guess you like

Origin blog.csdn.net/douzhq/article/details/104351363