关闭

CSemaphore semaphoreWrite(2,2);

标签: nullthreadattributesc
502人阅读 评论(0) 收藏 举报
分类:
/*
CSemaphore (LONG lInitialCount=1,
LONG lMaxCount=1,
LPCTSTR pstrName=NULL,
LPSECURITY_ATTRIBUTES lpsaAttributes=NULL);

  lInitialCount:信号量对象的初始计数值,即可访问线程数目的初始值; 
  lMaxCount:信号量对象计数值的最大值,该参数决定了同一时刻
  lMaxCount>=lInitialCount才行,否则报错!
  可访问由信号量保护的资源的线程最大数目; 
后两个参数在同一进程中使用一般为NULL,不作过多讨论;
*/
CSemaphore semaphoreWrite(2,2); //资源最多访问线程2个,当前可访问线程数2个 
char g_Array[10]; 
//添加三个线程函数: 

UINT WriteA(LPVOID pParam)
{
	CEdit *pEdit=(CEdit*)pParam;
	pEdit->SetWindowText("");
	WaitForSingleObject(semaphoreWrite.m_hObject,INFINITE);
	CString str;
	for(int i=0;i<10;i++)
	{
        pEdit->GetWindowText(str);
		g_Array[i]='A';
		str=str+g_Array[i];
		pEdit->SetWindowText(str);
		Sleep(1000);
	}
	ReleaseSemaphore(semaphoreWrite.m_hObject,1,NULL);
	return 0;
	
}
UINT WriteB(LPVOID pParam)
{
	CEdit *pEdit=(CEdit*)pParam;
	pEdit->SetWindowText("");
	WaitForSingleObject(semaphoreWrite.m_hObject,INFINITE);
	CString str;
	for(int i=0;i<10;i++)
	{
		
        pEdit->GetWindowText(str);
		g_Array[i]='B';
		str=str+g_Array[i];
		pEdit->SetWindowText(str);
		Sleep(1000);
	}
	ReleaseSemaphore(semaphoreWrite.m_hObject,1,NULL);
	return 0;
	
}
UINT WriteC(LPVOID pParam)
{
	CEdit *pEdit=(CEdit*)pParam;
	pEdit->SetWindowText("");
	WaitForSingleObject(semaphoreWrite.m_hObject,INFINITE);
	for(int i=0;i<10;i++)
	{
		g_Array[i]='C';
		pEdit->SetWindowText(g_Array);
		Sleep(1000);
	}
	ReleaseSemaphore(semaphoreWrite.m_hObject,1,NULL);
	return 0;
	
}


void CMultiThread10Dlg::OnStart() 
{
	CWinThread *pWriteA=AfxBeginThread(WriteA,
		&m_ctrlA,
		THREAD_PRIORITY_NORMAL,
		0,
		CREATE_SUSPENDED);
	pWriteA->ResumeThread();
	
	CWinThread *pWriteB=AfxBeginThread(WriteB,
		&m_ctrlB,
		THREAD_PRIORITY_NORMAL,
		0,
		CREATE_SUSPENDED);
	pWriteB->ResumeThread();
	
	CWinThread *pWriteC=AfxBeginThread(WriteC,
		&m_ctrlC,
		THREAD_PRIORITY_NORMAL,
		0,
		CREATE_SUSPENDED);
 pWriteC->ResumeThread();
	
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2977428次
    • 积分:40136
    • 等级:
    • 排名:第94名
    • 原创:399篇
    • 转载:4555篇
    • 译文:5篇
    • 评论:609条
    文章分类
    最新评论