您的位置:首页 > 其它

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

2007-03-05 15:10 197 查看
我们还是用上面的那个程序,要实现数据有序的读写,这次我们用互斥技术.

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 );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: