ivy-jie

progress ...

C++博客 首页 新随笔 联系 聚合 管理
  9 Posts :: 41 Stories :: 6 Comments :: 0 Trackbacks

在VC6下做的,在LINUX下,将临界换成互斥就OK了。
题目如下:
启动4个线程,向4个文件A,B,C,D里写入数据,每个线程只能写一个值。
线程1:只写1
线程2:只写2
线程3:只写3
线程4:只写4
4个文件A,B,C,D。
程序运行起来,4个文件的写入结果如下:
A:12341234。。。。
B:23412341。。。。
C:34123412。。。。
D:41234123。。。。

// Multithread.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <windows.h>
struct FILEINFO
{
  int curnumber;//写入的当前数据
  char filename[2];//文件名
  CRITICAL_SECTION cs;//临界
 
  FILEINFO()
  {
    curnumber = 0;
 InitializeCriticalSection(&cs);
 memset(filename,0,2);
  }
};

FILEINFO *pFileInfo =0;
const int MAXFILESIZE=4;
char szfilename[]="ABCD";
/////线程函数////////////////
DWORD WINAPI twritefile(LPVOID parm)
{
  int number =(int) parm;
  int nIndex = number-1;//保证线程i从文件i-1开始写
  FILE *fp;
  char szbuf[2];
  sprintf(szbuf,"%d",number);
  bool isfirst = true;
  char sztmp[16]={0};//用来保存文件名

  while(true)
  {
    if(nIndex ==MAXFILESIZE)
   nIndex = 0;
   EnterCriticalSection(&pFileInfo[nIndex].cs);
   if((number-pFileInfo[nIndex].curnumber)!=1 && !isfirst)
  {
     LeaveCriticalSection(&pFileInfo[nIndex].cs);
     nIndex++;
     continue;
   }
    sprintf(sztmp,"%s",pFileInfo[nIndex].filename);
   fp = fopen(sztmp,"a+b");
   if(fp!=0)
  {
    fwrite(szbuf,1,1,fp);
    fclose(fp);
    if(number==MAXFILESIZE)  //当为第4个线程时,文件结构的curnumber设置为0;否则,设置为线程ID
      pFileInfo[nIndex].curnumber=0;
   else
      pFileInfo[nIndex].curnumber = number;
  isfirst=false;
 }
  LeaveCriticalSection(&pFileInfo[nIndex].cs);
  nIndex++;
  }
}

  int main(int argc, char* argv[])
{
   pFileInfo = new FILEINFO[MAXFILESIZE];
   DWORD TID;

   for(int nIndex =0;nIndex<MAXFILESIZE;nIndex++)
  {
     pFileInfo[nIndex].filename[0] = szfilename[nIndex];
  }
  for(nIndex =1;nIndex<=MAXFILESIZE;nIndex++)
 {
    CreateThread(NULL,0,twritefile,(void*)nIndex,0,&TID);
 }
 while(1)
  Sleep(100000);

}

posted on 2009-06-11 23:55 ivy-jie 阅读(1335) 评论(0)  编辑 收藏 引用 所属分类: MFC

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理