1: // 线程实现2.cpp : 定义控制台应用程序的入口点。
2: //
3:
4: #include "stdafx.h"
5: #include
6: #include
7: using namespace std;
8:
9: DWORD WINAPI Fun1Proc(LPVOID lpParameter);//thread data
10: DWORD WINAPI Fun2Proc(LPVOID lpParameter);//thread data
11:
12: int index=0;
13: int tickets=10;
14: HANDLE hMutex;
15:
16: int _tmain(int argc, _TCHAR* argv[])
17: {
18: HANDLE hThread1;
19: HANDLE hThread2;
20: //创建线程
21:
22:
23: /*
24: HANDLE CreateThread(
25: LPSECURITY_ATTRIBUTES lpThreadAttributes, // pointer to security attributes
26: DWORD dwStackSize, // initial thread stack size
27: LPTHREAD_START_ROUTINE lpStartAddress, // pointer to thread function
28: LPVOID lpParameter, // argument for new thread
29: DWORD dwCreationFlags, // creation flags
30: LPDWORD lpThreadId // pointer to receive thread ID
31: );
32: 第一个参数是指向SECURITY_ATTRIBUTES型态的结构的指针。在Windows 98中忽略该参数。在Windows NT中,它被设为NULL
33: 第二个参数是用于新线程的初始堆栈大小,默认值为0, 表示1MB。在任何情况下,Windows根据需要动态延长堆栈的大小。
34: 第三个参数是指向线程函数的指标。函数名称没有限制,但是必须以下列形式声明:DWORD WINAPI ThreadProc (PVOID pParam) ; 返回值为DWORD,调用约定是WINAPI
35: 调用约定:
36: 除了c pascal stdcall之外,什么时候又来一个WINAPI调用约定(calling conversion)呢?哦WINAPI在WINDEF.h中被定义为:#define WINAPI __stdcall
37: 第四个参数为传递给ThreadProc的参数。这样主线程和从属线程就可以共享数据。
38: 第五个参数通常为0,但当建立的线程不马上执行时为旗标CREATE_SUSPENDED。线程将暂停直到呼叫ResumeThread来恢复线程的执行为止。默认情况是立即执行
39: 第六个参数:新线程ID会被传回这里
40: */
41:
42: hThread1=CreateThread(
43: NULL, //1
44: 0, //2
45: Fun1Proc, //3
46: NULL, //4
47: 0, //5
48: NULL); //6
49: hThread2=CreateThread(
50: NULL,
51: 0,
52: Fun2Proc,
53: NULL,
54: 0,
55: NULL);
56: CloseHandle(hThread1);
57: CloseHandle(hThread2);
58:
59: //创建互斥对象
60: hMutex=CreateMutex(NULL,TRUE,_T("tickets"));
61: if (hMutex)
62: {
63: if (ERROR_ALREADY_EXISTS==GetLastError())
64: {
65: cout<<"only one instance can run!"<<endl;
66: return 0;
67: }
68: }
69: WaitForSingleObject(hMutex,INFINITE);
70: ReleaseMutex(hMutex);
71: ReleaseMutex(hMutex);
72:
73: Sleep(4000);
74: system("pause");
75: return 0;
76: }
77:
78: DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data
79: {
80: while (true)
81: {
82: ReleaseMutex(hMutex);
83: WaitForSingleObject(hMutex,INFINITE);
84: if (tickets>0)
85: {
86: Sleep(1);
87: cout<<"thread1 sell ticket :"<<tickets--<<endl;
88: }
89: else
90: break;
91: ReleaseMutex(hMutex);
92: }
93:
94: return 0;
95: }
96: //线程2的入口函数
97: DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data
98: {
99: while (true)
100: {
101: ReleaseMutex(hMutex);
102: WaitForSingleObject(hMutex,INFINITE);
103: if (tickets>0)
104: {
105: Sleep(1);
106: cout<<"thread2 sell ticket :"<<tickets--<<endl;
107: }
108: else
109: break;
110: ReleaseMutex(hMutex);
111: }
112: return 0;
113: }
114: