码迷,mamicode.com
首页 > 编程语言 > 详细

C线程同步/异步

时间:2014-10-10 19:00:14      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   sp   div   

bubuko.com,布布扣
 1 #include<windows.h>
 2 #include<stdio.h>
 3 #include<string.h>
 4 //#include <afxmt.h>
 5 #define T_MAX 100
 6 int  ticket;
 7 CRITICAL_SECTION CriticalSection;
 8 /* //售票线程
 9 DWORD WINAPI SaleThread(LPVOID lp)
10 {
11 int n = (int) lp;
12 while (ticket > 0)
13 {
14 printf("SaleThread%d sell %dth ticket\n", n, T_MAX-ticket+1);
15 ticket--;
16 Sleep(500);
17 }
18 return 0;
19 }
20 
21 void MyThread()
22 {
23 HANDLE handle1,handle2,handle3,handle4,handle5;
24 //5个售票线程
25 handle1 = CreateThread(NULL,NULL,SaleThread,(void*)1,NULL,NULL);
26 handle2 = CreateThread(NULL,NULL,SaleThread,(void*)2,NULL,NULL);
27 handle3 = CreateThread(NULL,NULL,SaleThread,(void*)3,NULL,NULL);
28 handle4 = CreateThread(NULL,NULL,SaleThread,(void*)4,NULL,NULL);
29 handle5 = CreateThread(NULL,NULL,SaleThread,(void*)5,NULL,NULL);
30 }
31 */
32 
33 //售票线程
34 DWORD WINAPI SaleThread(LPVOID lp)
35 {
36 int n = (int) lp;
37 while (ticket > 0)
38 { //临界区同步
39 EnterCriticalSection(&CriticalSection);
40 printf("SaleThread%d sell %dth ticket\n", n, T_MAX-ticket+1);
41 ticket--;
42 LeaveCriticalSection(&CriticalSection);
43 Sleep(500);
44 }
45 return 0;
46 }
47 void MyThread()
48 {
49 HANDLE handle1,handle2,handle3,handle4,handle5;
50 //5个售票线程
51 handle1 = CreateThread(NULL,NULL,SaleThread,(void*)1,NULL,NULL);
52 handle2 = CreateThread(NULL,NULL,SaleThread,(void*)2,NULL,NULL);
53 handle3 = CreateThread(NULL,NULL,SaleThread,(void*)3,NULL,NULL);
54 handle4 = CreateThread(NULL,NULL,SaleThread,(void*)4,NULL,NULL);
55 handle5 = CreateThread(NULL,NULL,SaleThread,(void*)5,NULL,NULL);
56 }
57 
58 int main(int argc, char* argv[])
59 {
60   ticket=100;
61 //创建临界区对象
62 InitializeCriticalSection(&CriticalSection);
63 if(ticket>0)
64 MyThread();
65 Sleep(50000);
66 //删除临界区对象
67 DeleteCriticalSection(&CriticalSection);
68 return 0;
69 }
View Code

 

C线程同步/异步

标签:style   blog   http   color   io   os   ar   sp   div   

原文地址:http://www.cnblogs.com/gongxijun/p/4016389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!