|
//mingw 3.02编译通过
1
#include
<
stdio.h
>
2
#include
<
stdlib.h
>
3
#include
<
windows.h
>
4
#include
<
openssl
/
md5.h
>
5
6
typedef
void
*
PVOID;
7
typedef
void
*
LPVOID;
8
9
10
DWORD WINAPI ThreadFunc(LPVOID);
11
12
int
main()
{
13
HANDLE hThrd1;
14
HANDLE hThrd2;
15
DWORD exitCode1
=
0
;
16
DWORD exitCode2
=
0
;
17
DWORD threadId;
18
19
20
/**/
/*
hThread = CreateThread (&security_attributes, dwStackSize, ThreadProc,pParam, dwFlags, &idThread)
21
WINBASEAPI HANDLE WINAPI CreateThread(LPSECURITY_ATTRIBUTES,DWORD,LPTHREAD_START_ROUTINE,PVOID,DWORD,PDWORD);
22
第一个参数是指向SECURITY_ATTRIBUTES型态的结构的指针。在Windows 98中忽略该参数。在Windows NT中,它被设为NULL。
23
第二个参数是用于新线程的初始堆栈大小,默认值为0。在任何情况下,Windows根据需要动态延长堆栈的大小。
24
第三个参数是指向线程函数的指标。函数名称没有限制,但是必须以下列形式声明:DWORD WINAPI ThreadProc (PVOID pParam) ;
25
第四个参数为传递给ThreadProc的参数。这样主线程和从属线程就可以共享数据。
26
第五个参数通常为0,但当建立的线程不马上执行时为旗标
27
第六个参数是一个指针,指向接受执行绪ID值的变量
28
*/
29
hThrd1
=
CreateThread(NULL,
0
, ThreadFunc, (LPVOID)
1
,
0
,
&
threadId );
//
建立第一个线程
30
if
(hThrd1)
31
printf(
"
Thread 1 执行\n
"
);
32
33
hThrd2
=
CreateThread(NULL,
0
, ThreadFunc, (LPVOID)
2
,
0
,
&
threadId );
34
if
(hThrd2)
35
printf(
"
Thread 2 执行\n
"
);
36
37
//
Keep waiting until both calls to GetExitCodeThread succeed AND
38
//
neither of them returns STILL_ACTIVE.
39
for
(;;)
{
40
printf(
"
按任意键退出..\n
"
);
41
getchar();
42
//
WaitForSingleObject();
43
GetExitCodeThread(hThrd1,
&
exitCode1);
//
取得线程函数的返回值
44
GetExitCodeThread(hThrd2,
&
exitCode2);
45
if
( exitCode1
==
STILL_ACTIVE )
46
puts(
"
Thread 1 正在执行状态!
"
);
47
if
( exitCode2
==
STILL_ACTIVE )
48
puts(
"
Thread 2 正在执行状态!
"
);
49
50
if
( exitCode1
!=
STILL_ACTIVE
&&
exitCode2
!=
STILL_ACTIVE )
51
break
;
52
}
53
54
CloseHandle(hThrd1);
55
CloseHandle(hThrd2);
56
57
printf(
"
Thread 1 returned %d\n
"
, exitCode1);
58
printf(
"
Thread 2 returned %d\n
"
, exitCode2);
59
getchar();
60
return
0
;
//
EXIT_SUCCESS;
61
}
62
63
/**/
/*
64
* Take the startup value, do some simple math on it,
65
* and return the calculated value.
66
*/
67
DWORD WINAPI ThreadFunc(LPVOID n)
{
68
Sleep((DWORD)n
*
1000
*
2
);
69
printf(
"
Thread %d 正在执行\n
"
,n);
70
return
(DWORD)n
*
10
;
71
}
72
|