跳至主要内容

9.线程控制

线程控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <handleapi.h>
#include <minwindef.h>
#include <processthreadsapi.h>
#include <stdio.h>
#include <synchapi.h>
#include <windows.h>
#include <winnt.h>


DWORD WINAPI ThreadProc(LPVOID IpParameter){
int *p = (int *) IpParameter;
for (int i = 0; i < *p; i++) {
Sleep(500);
printf("+++%d\n",i);
}
return 0;
}

int main(int argc, char *argv[]) {
HANDLE hThread;
int n;

n = 10;
hThread = CreateThread(NULL, 0, ThreadProc, (LPVOID)&n, 0, NULL);
Sleep(3000);
printf("Sleep!\n");
SuspendThread(hThread);
SuspendThread(hThread);
Sleep(1000);
ResumeThread(hThread);
Sleep(1000);
ResumeThread(hThread);

WaitForSingleObject(hThread, INFINITE);
printf("Thread Done");
//getchar();
CloseHandle(hThread);
return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <handleapi.h>
#include <minwindef.h>
#include <processthreadsapi.h>
#include <stdio.h>
#include <synchapi.h>
#include <windows.h>
#include <winnt.h>


DWORD WINAPI ThreadProc(LPVOID IpParameter){
for (int i = 0; i < 100; i++) {
Sleep(50);
printf("+++%d\n",i);
}
return 0;
}

int main(int argc, char *argv[]) {
HANDLE hThread[2];
DWORD dwR1,dwR2;
hThread[0] = CreateThread(NULL, 0, ThreadProc, NULL,0, NULL);
hThread[1] = CreateThread(NULL, 0, ThreadProc, NULL,0, NULL);

WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
GetExitCodeThread(hThread[0], &dwR1);
GetExitCodeThread(hThread[1], &dwR2);
printf("%lx %lx",dwR1,dwR2);
return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <handleapi.h>
#include <minwindef.h>
#include <processthreadsapi.h>
#include <stdio.h>
#include <synchapi.h>
#include <windows.h>
#include <winnt.h>


DWORD WINAPI ThreadProc(LPVOID IpParameter){
for (int i = 0; i < 100; i++) {
Sleep(50);
printf("+++%d\n",i);
}
return 0;
}

int main(int argc, char *argv[]) {
HANDLE hThread[2];
CONTEXT context;
hThread[0] = CreateThread(NULL, 0, ThreadProc, NULL,0, NULL);
hThread[1] = CreateThread(NULL, 0, ThreadProc, NULL,0, NULL);

SuspendThread(hThread[0]);
context.ContextFlags = CONTEXT_INTEGER;
GetThreadContext(hThread[0], &context);
printf("%llx %llx \n",context.Rax,context.Rcx);
//SetThreadContext();
ResumeThread(hThread[0]);

WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
return 0;
}

关于本文

由 GuQing 撰写,采用 CC BY-NC 4.0 许可协议。