zoukankan      html  css  js  c++  java
  • win32 线程通信初步

    // 线程通信机制.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #define  NUM_THREADS 10
    #include <windows.h>
    #include <stdio.h>
    #include <process.h>
    
    typedef struct
    {
     int Id;
     HANDLE hTerminate;
    
    }ThreadArgs;
    
    unsigned __stdcall ThreadFunc(void *pArgs)
    {
    	HANDLE hTerminate = ((ThreadArgs *)pArgs)->hTerminate;//参数转换
    	int id = ((ThreadArgs *)pArgs)->Id;
    
    	//运行到我们被告知需要终止的时候
    	while(1)
    	{
    		//检查我们是否需要终止
    		if(WaitForSingleObject(hTerminate,0) == WAIT_OBJECT_0)
    		{
    			//终止线程--我们调用ResetEvent来讲终止的线程返回到非激发状态之后,推出while循环
    			printf("Terminating Thread %d 
    ",id);
    			ResetEvent(hTerminate);
    			break;
    		}
    		
    		//我们现在可以处理我们的工作,模拟这个情况,假设工作需要1秒钟来做线程需要做的工作
    
    		Sleep(1000);
    
    	}
    
    	_endthreadex(0);
    
    	return 0;
    
    }
    
    int main(int argc ,char * argv[])
    {
    	unsigned int threadID[NUM_THREADS];
    	HANDLE hThread[NUM_THREADS];
    	ThreadArgs threadArgs[NUM_THREADS];
    
    	//创建10个线程 
    	for(int i =0 ; i < NUM_THREADS ; i++)
    	{
    		threadArgs[i].Id = i;
    		threadArgs[i].hTerminate = CreateEvent(NULL, TRUE, FALSE, NULL);
    		hThread[i] = (HANDLE)_beginthreadex(NULL, 0, &ThreadFunc, &threadArgs[i], 0, &threadID[i]);
    	}
    
    	printf("To kill a thread (gracefully), press 0-9, then <Enter>.
    ");
    	printf("Press any other key to exit .
    ");
    
    	while (1)
    	{
    		int c = getc(stdin);
    		if (c == '
    ')
    		{
    			continue;
    		}
    		if (c<'0'||c>'9')
    		{
    			break;
    		}
    		SetEvent(threadArgs[c - '0'].hTerminate);
    	}
    	return 0;
    }
    
    
    


     

  • 相关阅读:
    redis总结
    java程序启动脚本
    mysql生成百万测试数据脚本
    java分布式锁的实现及在springboot中的应用
    mysql使用总结
    一个java实现代码(服务)编排的思路(未完)
    sentinel自定义统一限流降级处理
    shell学习
    oracle查看被锁的事务进程sql
    Sql查询两个时间段有重叠的记录
  • 原文地址:https://www.cnblogs.com/wangyaning/p/4236956.html
Copyright © 2011-2022 走看看