线程学习手记

关键代码的使用


CRITICAL_SECTION g_cs;   //关键代码的
DWORD num;

void mainfun(void)
{
 	EnterCriticalSection(&g_cs);  //进入关键代码
	num++;
	printf("%d\n",num);
                    LeaveCriticalSection(&g_cs);  //
}
DWORD CALLBACK ThreadFun(LPVOID param)
{
		while(1)
		{
		mainfun();
		}
}
DWORD CALLBACK ThreadFun1(LPVOID param)
{
	while(1)
	{
	mainfun();
	}

}
int main(int argc, char* argv[])
{

	num=0;
	InitializeCriticalSection(&g_cs);  //关键代码初使化
	createThread(NULL,NULL,ThreadFun,NULL,0,&th1);
	createThread(NULL,NULL,ThreadFun1,NULL,0,&th2);
                     Sleep(20000);
                    deleteCiriticalSection(&g_cs);

	return 0;
}

用起来很简单就这样..就看用在哪里了..

事件内核对像,刚开始学编程的时候就碰到了!今天就把这个砌底的学习一下,


#include "windows.h"
#include "stdio.h"
HANDLE hevent1;
HANDLE hevent2;
DWORD CALLBACK threadfun1 (LPVOID  param)
{
	DWORD num=0;
	while(1)
	{
	WaitForSingleObject(hevent1,INFINITE);
	printf("Thread 1 Beging .....\n");
	printf("%d\n",num++);
	Sleep(500);
	if(num==10)
	{
		SetEvent(hevent2);  //开启线程二
		ResetEvent(hevent1);  //暂停本线程
		num=0;
	}

	}
}

DWORD CALLBACK threadfun2 (LPVOID param)
{
	  int i=0;
	  while(1)
	  {

	  WaitForSingleObject(hevent2,INFINITE);    //等待事件的发生

	  printf("thread 2 Beging ......\n");
	  Sleep(500);
	  printf("%d\n",i++);

	  if(i==10)
	  {
		  SetEvent(hevent1);  //开线程1
		  ResetEvent(hevent2); //暂停自己
		  i=0;
	  }

	  }
}

	void main()
 {

	hevent1 = createEvent(NULL , TRUE,1 , "GLEON");   //参数(3)为一创建就是通知状态
	hevent2 = createEvent(NULL , TRUE,0 , "GLEON1");   //
	createThread(NULL,0,threadfun1,NULL,0,NULL);
	SetEvent(hevent1);
	createThread(NULL,0,threadfun2,NULL,0,NULL);
	while(1)
	{
		Sleep(100000);
	}
	CloseHandle(hevent1);
	CloseHandle(hevent2);
 }

随机日志

发表评论

0 评论.

Leave a Reply



[ Ctrl + Enter ]

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

CNXCT小组的博客 is Stephen Fry proof thanks to caching by WP Super Cache