在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);
}