有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四 个文件呈如下格式:A:1 2 3 4 1 2....B:2 3 4 1 2 3....C:3 4 1 2 3 4....D:4 1 2 3 4 1....请设计程序。
- #include <stdio.h>
- #include <process.h>
- #include <windows.h>
- #include <fstream.h>
- #include <string.h>
-
-
- unsigned int __stdcall Fun(void *pPM);
-
- const int THREAD_NUM = 4;
- const int FILE_NUM = 4;
-
- ofstream ofile[FILE_NUM];
-
- int FILE_THREAD[FILE_NUM]={0,1,2,3};
- int NEXT_LOOP[FILE_NUM]={0,1,2,3,};
-
- CRITICAL_SECTION g_csFile;
-
- const int LOOP = 6;
-
- HANDLE g_hThreadEvent[THREAD_NUM];
-
-
- int main()
- {
- printf("\t有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2\n");
- printf("以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式\n");
-
- int i = 0 , j;
- HANDLE hdl[THREAD_NUM];
- InitializeCriticalSection(&g_csFile);
-
-
- for (i = 0; i < THREAD_NUM; i++)
- g_hThreadEvent[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
-
-
-
- char FILE_THREAD[] ="A.txt";
-
- for (i = 0; i < FILE_NUM; i++)
- {
-
- FILE_THREAD[0] = i + ‘A‘;
- ofile[i].open(FILE_THREAD,ios::trunc);
-
- if(ofile[i].fail())
- {
- printf("打开文件%s 失败",FILE_THREAD);
- continue;
- }
- }
-
- for (i = 0; i < THREAD_NUM; i++)
- hdl[i] = (HANDLE)_beginthreadex(NULL,0,Fun,(void*)i,0,NULL);
-
-
-
- SetEvent( g_hThreadEvent[0] );
-
-
- WaitForMultipleObjects(THREAD_NUM,hdl,TRUE,INFINITE);
-
-
- for (i = 0; i < THREAD_NUM; i++)
- {
- CloseHandle(hdl[i]);
- CloseHandle(g_hThreadEvent[i]);
- }
-
- for( i = 0 ; i< FILE_NUM;i++)
- {
- ofile[i].close();
- }
- DeleteCriticalSection(&g_csFile);
-
- return 0;
- }
-
- unsigned int __stdcall Fun(void *pPM)
- {
-
- int num = (int)pPM ;
- int i = 0;
- for( i = 0 ; i< LOOP;i++)
- {
-
- WaitForSingleObject(g_hThreadEvent[num],INFINITE);
-
- EnterCriticalSection(&g_csFile);
-
- printf(" 线程 %d 正在向%c文件写入,下一次对文件%c操作的是线程%d\n",
- num + 1 , FILE_THREAD[num] + ‘A‘,FILE_THREAD[num] + ‘A‘,(num+1)%(THREAD_NUM) +1);
-
- ofile[FILE_THREAD[num]]<<num+1<<" ";
-
- Sleep(200);
-
-
- NEXT_LOOP[ (num+1)%(FILE_NUM) ] = FILE_THREAD[num] ;
-
- if( num + 1 == FILE_NUM)
- {
- printf("\n");
-
- memcpy(&FILE_THREAD,&NEXT_LOOP,FILE_NUM *sizeof(int));
- }
-
- LeaveCriticalSection(&g_csFile);
-
-
- SetEvent(g_hThreadEvent[(num+1)%THREAD_NUM ]);
- }
- return 0;
- }