c语言多线程实例

在这里插入图片描述


#include "stdafx.h"
#include<windows.h>
#include <stdio.h>
HANDLE hFile;
//定义临界区
CRITICAL_SECTION cs;

DWORD WINAPI Thread(LPVOID lpParam)
{
    
    
	//得到线程的编号
	int n = (int)lpParam;
	DWORD dvWrite;
	for (int i = 0; i < 10000; i++){
    
    
		//进入临界区
		EnterCriticalSection(&cs);
		char Data[512] = "\r\n--------------by chen-----------\r\n--------------http://www.baidu.com/--------";
		//写入文件
		WriteFile(hFile, &Data, strlen(Data), &dvWrite, NULL);
		//离开临界区
		LeaveCriticalSection(&cs);
	}
	//输出哪个线程运行结束
	printf("the number %d thread run end \n", n);
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    
    
	//创建文件
	hFile = CreateFile("c:\\hack.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE){
    
    
		printf("CreateFile Error!\n");
	}

	DWORD ThreadId;
	HANDLE hThread[5];
	//初始化临界区对象
	InitializeCriticalSection(&cs);

	//创建5个线程
	for (int i = 0; i < 5; i++){
    
    
		hThread[i] = CreateThread(NULL, NULL, Thread, LPVOID(i+1),0,&ThreadId);
		printf("the number %d thread create success!\n", i + 1);
	}
	//等待五个线程运行结束
	WaitForMultipleObjects(5, hThread, true, INFINITE);
	//删除临界区对象
	DeleteCriticalSection(&cs);
	//关闭文件句柄
	CloseHandle(hFile);
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/chendongpu/article/details/121371761