互斥量(Mutex)跟临界区很相似,只有拥有互斥对象的线程才具有访问资源的权限,由于互斥对象只有一个,因此就是就决定了任何情况下此共享资源都不会同时被多个线程访问。当前占据资源的线程在任务处理完后将拥有的互斥对象交出,以便其他线程在获得后得以访问资源。互斥量比临界区复杂。因此使用互斥不仅能够在同一应用程序不同线程中实现资源的安全共享,而且可以在不同应用程序的线程之间实现对资源的安全共享。
下面是一个在Linux下使用Mutex的多线程例子:
#include<stdio.h>
#include<pthread.h>
pthread_mutex_t mutex;
int counter=0;
void *thread_function(void *dummyPtr)
{
printf("Thread numer%ld\n",pthread_self());
pthread_mutex_lock(&mutex);
counter++;
pthread_mutex_unlock(&mutex);
}
void main()
{
pthread_t thread_id[10];
int i,j;
pthread_mutex_init(&mutex,NULL);
for(i=0;i<10;i++)
{
pthread_create(&thread_id[i],NULL,thread_function,NULL);
}
for(j=0;j<10;j++)
{
pthread_join(thread_id[j],NULL);
}
printf("Final counter value:%d\n",counter);
}
下面是Windows下的Mutex的多线程的例子:
#include <windows.h>
#include <iostream.h>
HANDLE hMutex;
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"thread1 is running"<<endl;
ReleaseMutex(hMutex);
return 0;
}
DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
WaitForSingleObject(hMutex,INFINITE);
cout<<"thread2 is running"<<endl;
ReleaseMutex(hMutex);
return 0;
}
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
Sleep(4000);
}