跳至主要内容

8.创建线程

线程

  • 线程是附属在进程上的执行实体,是代码的执行流程
  • 一个进程可以包含多个线程,但是一个进程至少要包含一个线程

创建线程

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
#include <handleapi.h>
#include <minwindef.h>
#include <processthreadsapi.h>
#include <stdio.h>
#include <synchapi.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);
CloseHandle(hThread);
for (int i = 0; i < 100; i++) {
Sleep(500);
printf("---%d \n",i);
}
return 0;
}

关于本文

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