C-多线程读写同步

来源:互联网 发布:tb6612fng数据手册 编辑:程序博客网 时间:2024/05/17 07:32

网易公开课,多线程读写同步,VS2010控制台程序:

// testVC.cpp : 读写同步实现。
//
#include "stdafx.h"
#define BUFFLENGTH 8
char buffer[BUFFLENGTH];
HANDLE hSemaphoreEmpty;
HANDLE hSemaphoreFull;
DWORD _stdcall Reader(LPVOID lpParameter);
DWORD _stdcall Writer(LPVOID lpParameter);
int main(int argc, char* argv[])
{
 HANDLE handle[2];
 hSemaphoreEmpty = CreateSemaphore(NULL, 8, 8, NULL);
 hSemaphoreFull = CreateSemaphore(NULL, 0, 8, NULL);
 handle[0] = CreateThread(NULL,0,Writer,NULL, 0, NULL);
 handle[1] = CreateThread(NULL,0,Reader,NULL, 0, NULL);
 WaitForMultipleObjects(2,handle,TRUE,INFINITE);
 return 0;
}
DWORD _stdcall Writer(LPVOID lpParameter)
{
 char str[41];
 for(int i=0;i<40;i++){
  str[i] = 'A' + rand() % 26;
  WaitForSingleObject(hSemaphoreEmpty, INFINITE);
  buffer[i%BUFFLENGTH] = str[i];
  ReleaseSemaphore(hSemaphoreFull, 1, NULL);
 }
 str[40] = '\0';
 printf("Writer:%s\n",str);
 return 0;
}
DWORD _stdcall Reader(LPVOID lpParameter)
{
 char str[41];
 for(int i=0;i<40;i++){
  WaitForSingleObject(hSemaphoreFull, INFINITE);
  str[i] = buffer[i%BUFFLENGTH];
  ReleaseSemaphore(hSemaphoreEmpty, 1, NULL);
 }
 str[40] = '\0';
 printf("Reader:%s\n",str);
 return 0;
}