多线程程序设计过程中比较难控制的是线程之间的同步.对于线程同步的解决有如下四种办法.一是用临界量;二是用互斥;三是事件;四是信号量.
void main()
{
HANDLE thread1;
DWORD d1;
CloseHandle( thread1 );
}
void main()
{
HANDLE thread1;
DWORD d1;
CloseHandle( thread1 );
}
临界量是指提供对线程控制的对象来控制线程.就向令牌一样,谁有谁操作临界区.下面有二个例子:
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 );
}
这是我们会发现程序输出不稳定,有不确定的因素.怎么办呢,我们要加入线程之间的同步控制.下面我介绍几个函数.
一是InitialCriticalSection();
二是EnterCriticalSection();
三是LeaveCriticalSection();
四是DeleteCtriticalSection();
五是TryEnterCtriticalSection();
好了,我们把上面的程序加入临界区的控制技术,再看看输出吧.
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];
CRITICAL_SECTION cs;
DWORD WINAPI Thread1(LPVOID lpParamter)
{
while(true)
{
{
while(true)
{
EnterCriticalSection(&cs);
for(int i = 0; i<5; i++)
{
a[i] = i ;
}
for(int i = 0; i<5; i++)
{
a[i] = i ;
}
LeaveCriticalSection(&cs);
}
}
return 0 ;
}
}
void main()
{
HANDLE thread1;
DWORD d1;
InitialCriticalSection(&cs);
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)
{
{
EnterCriticalSection(&cs);
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;
LeaveCriticalSection(&cs);
}
CloseHandle( thread1 );
}
好了,这样就基本上可以控制数据之间的同步了.