我们还是用上面的那个程序,要实现数据有序的读写,这次我们用互斥技术.
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互斥量(Mutex)来同步访问共享资源的方法,有效防止了数据混乱。

308

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



