线中的互斥量
2016-01-15 09:06
239 查看
多个线程使用同一个变量,可以用互斥体进行保护。
#include <windows.h> #include <stdio.h> #pragma hdrstop #pragma argsused #define NUM_THREADS 4 DWORD dwCounter = 0; HANDLE hMutex; //声明互斥变量 void UseMutex(void); DWORD WINAPI MutexThread(LPVOID lpParam); int a[4]={1,2,3,4}; //--------------------------------------------------------------------------- int main(int argc, char* argv[]) { UseMutex(); getchar(); return 0; } //--------------------------------------------------------------------------- void UseMutex() { int i; HANDLE hThread; //创建互斥变量,第二个参数为初始状态,如果为true,则互斥量为当前进程拥有 //需要ReleaseMutes线程回调函数才能运行 hMutex = CreateMutexA(NULL,false,NULL); if(hMutex == NULL) { printf("互斥量创建不成功: %d\n",GetLastError()); } else { printf("创建互斥量成功!\n"); } for(i = 0;i< NUM_THREADS ;i++) { printf("创建线程 %d\n",i); hThread = CreateThread(NULL,0,MutexThread,&a[i],0,NULL);//创建线程 if(hThread == NULL) { printf("创建线程不成功(%d)\n",GetLastError()); return; } } Sleep(1000); CloseHandle(hMutex);//销毁互斥 } DWORD WINAPI MutexThread(LPVOID lpParam)//线程回调函数 { DWORD dwWaitResult; dwWaitResult = WaitForSingleObject(hMutex,INFINITE);//等待互斥量 switch(dwWaitResult) { case WAIT_OBJECT_0: Sleep(rand()%100); printf("counter :%d lpPrarm %d\n",dwCounter,*(int *)lpParam); dwCounter++; if(!ReleaseMutex(hMutex))//离开互斥区域,销毁互斥量CloseHandle { printf("释放互斥量错误 %d\n",GetLastError()); } break; default: printf("等待超时错误:%d\n",GetLastError()); ExitThread(0); } return 1; }
相关文章推荐
- Vim命令合集
- Apriori算法的JAVA实现
- 怎么计算apk的启动时间
- 关于myeclipse项目导入到eclipse 标签库以及The superclass "javax.servlet.http.HttpServlet" was not found没有发现
- 错误代码:Your build settings specify a provisioning profile with the UUID “”, however, no such provisioning profile was found
- MySQL配置文件my.cnf详解
- 项目记录16---打包手机andrid,ios资源打包读取配置xml错误,中文读取错误
- MMDrawerController第三方抽屉裤 如何打开和关闭侧滑
- poj2763 树链剖分(线段树)
- 修改grub 启动项
- Xcode7真机调试
- LeetCode Spiral Matrix II
- AngularJS + ui-router + RequireJS异步加载注册controller/directive/filter/service
- 批量修改AD用户属性python脚本
- CvArr、Mat、CvMat、IplImage、BYTE转换
- 3ds文件格式转openGL
- windows7 图形界面远程 centos6.5
- TIM_READ2
- dwz框架---(2)表单回调函数
- MySQL5.7多实例自动化部署脚本