C++ 同步对象解决有限缓冲区问题(基于线程)

来源:百度知道 编辑:UC知道 时间:2024/07/07 04:15:11
基于线程,实现有限缓冲区互斥访问.下面有初步的设想,如果有知道的人可以说一下哈.
(送150分)
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
#include <fstream.h>
#include <stdio.h>
#include <time.h>
#define INTE_PER_SEC 500
#define MAX_THREAD_NUM 64
#define RIGHT_VERSION TRUE
#define WRONG_VERSION FALSE
CRITICAL_SECTION my_section;
struct ThreadInfo
{
int serial;
double delay;
};
/*volatile*/ int accnt1 = 0;
/*volatile*/ int accnt2 = 0;
/*volatile*/ int accnt;
void account( char* file,BOOL version);
void acc_right(void* p);
void acc_wrong(void* p);
////////////////////////////////////////////////////////
// main function
////////////////////////////////////////////////////////
int main( int agrc, char* argv[] )
{
char ch;
while ( TRUE )
{
// Clear screen
system( "cls" );
// disp

只用过java的线程,对这个不熟悉.
似乎在c++编程艺术里看到过直接用函数可以设置互斥信号量.

win32 c里面本来就有互斥信号的类型,不过我比较习惯用事件等待来处理互斥。
可以创建一个HANDLE类型的Event,CreateEvent时是TRUE,TRUE,表示初始化后就Active,等待后自动复位。两个线程都用WaitForSingleObject等待,这样的好处是等待的时候不占CPU,当然这时候谁快谁先得,用完以后就SetEvent。

下面是一些例程代码。

HANDLE event=CreateEvent(NULL,FALSE,FALSE,NULL);
--------------------------------------
Threat1(LPVOID pParam ){
......
while(1){
......
WaitForSingleObject(evnet,INFINITE);
.....
SetEvent(event);
}
.....
}
--------------------------------
Threat1(LPVOID pParam ){
......
while(1){
......
WaitForSingleObject(evnet,INFINITE);
.....
SetEvent(event);
}
.....
}