互斥量(mutex)

互斥量(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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值