多个线程互同步问题
2011-09-22 15:41
337 查看
#include <windows.h> #include <stdio.h> #define NUMTHREADS 3 #define BUFFER_SIZE 16 #define FOR_TIMES 5 HANDLE hWriteEvents[NUMTHREADS]; HANDLE hReadEvents[NUMTHREADS]; BYTE lpSharedBuffer[16]={0}; void MultiEvents(void); VOID WriteToBuffer(VOID); DWORD WINAPI ThreadFunction(LPVOID lpParam); int main(){ MultiEvents(); } void MultiEvents(void){ HANDLE hThread; DWORD i; for(i=0;i<NUMTHREADS;i++){ hWriteEvents[i] = CreateEvent(NULL,FALSE,FALSE,NULL); if(hWriteEvents[i]==NULL){ printf("CreateEvent failed.(%d)\n",GetLastError()); return; } hReadEvents[i] = CreateEvent(NULL,FALSE,FALSE,NULL); if(hReadEvents[i]==NULL){ printf("CreateEvent failed.(%d)\n",GetLastError()); return; } hThread = CreateThread(NULL,0,ThreadFunction,i,0,NULL); if(hThread == NULL){ printf("CreateThread failed.(%d)\n",GetLastError()); return; } } WriteToBuffer(); } VOID WriteToBuffer(VOID){ DWORD dwWaitResult,i,j; for(j=0;j<FOR_TIMES;j++){ Sleep(rand()%100); wsprintf(lpSharedBuffer,"shared %d",j); for(i=0;i<NUMTHREADS;i++){ if(!SetEvent(hWriteEvents[i])){ printf("SetEvent failed.(%d)\n",GetLastError()); return; } } dwWaitResult = WaitForMultipleObjects(NUMTHREADS,hReadEvents,TRUE,INFINITE); if(dwWaitResult != WAIT_OBJECT_0){ printf("Wait error.(%d)\n",GetLastError()); ExitProcess(0); } } } DWORD WINAPI ThreadFunction(LPVOID lpParam){ DWORD dwWaitResult; BYTE lpRead[16]; DWORD j = 0; DWORD dwThreadIndex = (DWORD)lpParam; for(j=0;j<FOR_TIMES;j++){ dwWaitResult = WaitForSingleObject(hWriteEvents[dwThreadIndex],INFINITE); switch (dwWaitResult){ case WAIT_OBJECT_0: Sleep(rand()%10); CopyMemory(lpRead,lpSharedBuffer,16); break; default: printf("Wait error:%d\n",GetLastError()); return 0; } printf("线程%u\t第%d次读,内容:%s\n",dwThreadIndex,j,(LPSTR)lpRead); } return 1; }
本文出自 “About:Blank H4cking” 博客,请务必保留此出处http://pnig0s1992.blog.51cto.com/393390/671381
相关文章推荐
- 主线程与用户线程同步问题
- 多线程补充、多线程问题及处理、线程的同步及相关内容
- Java线程同步问题synchronized
- java中同步synchronized的意义,如何用它解决线程不安全的问题
- Java线程安全问题与同步锁
- 进程、线程知识点总结和同步(消费者生产者,读者写者三类问题)、互斥、异步、并发、并行、死锁、活锁的总结
- Java线程同步问题
- 黑马程序员------多线程(No.1)(概述、线程的创建、安全问题、同步锁、同步函数)
- Delphi中多线程用Synchronize实现VCL数据同步显示 解决在线程中操作控件出现问题
- Java线程(八):锁对象Lock-同步问题更完美的处理方式
- Java线程:线程的同步与锁 一、同步问题提出 线程的同步是为了防止多个线程访问一个数据对象时,对数据造成的破坏。 例如:两个线程ThreadA、ThreadB都操作同一个对象Foo对
- jdk线程的同步问题
- 线程问题——同步和死锁
- java线程的同步安全问题三种解决办法
- Java线程(八):锁对象Lock-同步问题更完美的处理方式
- Java/Android多线程并发、同步,线程之间通信,主、子线程的一些问题(CountDownLatch、CyclicBarrier和Semaphore)
- 进程(线程)间的同步互斥问题(五) 读者-作者问题
- 关于线程和进程的同步问题
- Java线程(八):锁对象Lock-同步问题更完美的处理方式
- 利用线程的同步和互斥解决两个消费者两个生产者一个临界区问题