我们还是用上面的那个程序,要实现数据有序的读写,这次我们用互斥技术.
example1.c
#include<iostream.h>
#include<process.h>
#include<windows.h>
#include<stdio.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 ;
}
}
{
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;
}
if(thread1 == NULL)
{
cout<<"create thread fail......"<<endl;
}
while(1)
{
for(int i = 0; i<5; i++)
{
cout<<a[0]<<" ";
}
cout<<endl<<""<<endl;
{
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>
#include<process.h>
#include<windows.h>
#include<stdio.h>
int a[5];
HANDLE hMutex ;
DWORD WINAPI Thread1(LPVOID lpParamter)
{
while(true)
{
{
while(true)
{
WaitForSingleObject(hMutex,INFINITE);
for(int i = 0; i<5; i++)
{
a[i] = i ;
}
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;
}
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;
for(int i = 0; i<5; i++)
{
cout<<a[0]<<" ";
}
cout<<endl<<""<<endl;
ReleaseMutex(hMutex);
}
CloseHandle( thread1 );
本文通过两个示例程序演示了如何利用Windows API中的互斥量(Mutex)来确保多线程环境中数据的有序读写。第一个示例程序在没有使用互斥量的情况下直接进行数据操作;第二个示例程序则展示了如何使用互斥量来保护数据的一致性和完整性。
1655

被折叠的 条评论
为什么被折叠?



