多线程式同步之互斥技术的应用

本文通过两个示例程序演示了如何利用Windows API中的互斥量(Mutex)来确保多线程环境中数据的有序读写。第一个示例程序在没有使用互斥量的情况下直接进行数据操作;第二个示例程序则展示了如何使用互斥量来保护数据的一致性和完整性。

我们还是用上面的那个程序,要实现数据有序的读写,这次我们用互斥技术.

example1.c
#include<iostream.h>
#include<process.h>
#include<windows.h>
#include<stdio.h>
int a[5];
DWORD WINAPI Thread1(LPVOID lpParamter)
{
while(true)
{
for(int i = 0; i<5; i++)
{
a[i] = i ;
}
}
return 0 ;
}

void main()
{
HANDLE thread1;
DWORD d1;
thread1 = CreateThread(NULL,0,Thread1,NULL,0,&d1);
if(thread1 == NULL)
{
cout<<"create thread fail......"<<endl;
}
while(1)
{
for(int i = 0; i<5; i++)
{
cout<<a[0]<<" ";
}
cout<<endl<<""<<endl;
}

CloseHandle( thread1 );
example2.c
#include<iostream.h>
#include<process.h>
#include<windows.h>
#include<stdio.h>
int a[5];
HANDLE hMutex ;
DWORD WINAPI Thread1(LPVOID lpParamter)
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
for(int i = 0; i<5; i++)
{
a[i] = i ;
}
ReleaseMutex(hMutex);
}
return 0 ;
}

void main()
{
HANDLE thread1;
DWORD d1;
hMutex = CreateMutex(NULL,FALSE,NULL);
thread1 = CreateThread(NULL,0,Thread1,NULL,0,&d1);
if(thread1 == NULL)
{
cout<<"create thread fail......"<<endl;
}
while(1)
{
WaitForSingleObject(hMutex,INFINITE);
for(int i = 0; i<5; i++)
{
cout<<a[0]<<" ";
}
cout<<endl<<""<<endl;
ReleaseMutex(hMutex);
}

CloseHandle( thread1 );
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值