本文详细介绍了在C++编程语言中实现多线程的方法,包括如何创建、暂停(挂起)、运行及终止线程。通过实例分析帮助读者掌握线程操作技巧。
1. 创建一个基于对话框的应用程序,并增加如图所示的控件:分别为三个进度条控件关联三个进度条类型的变量;并在对话框的初始化函数中设定这三个进度条的范围;为编辑框关联一个整型变量;为十二个按钮添加消息处理函数。
2. 定义结构体,用于线程函数参数传递:
```c
typedef struct Threadinfo {
CProgressCtrl *progress; // 进度条对象指针
int speed; // 速度值
int pos; // 当前位置
} thread, *lpthread;
```
3. 在对话框中增加三个句柄,用于标识各个线程:
```c
HANDLE hThread1; // 线程1的句柄
HANDLE hThread2; // 线程2的句柄
HANDLE hThread3; // 线程3的句柄
// 并增加三个结构体类型的变量,用于传递线程函数参数:
thread thread1;
thread thread2;
thread thread3;
```
4. 新增一个静态全局变量,用以记录所有线程的状态:
```c
static int GlobalVar = 10000; // 初始化为10000
```
5. 声明并实现线程函数。注意只能有一个参数,并且返回值类型固定;可以自定义函数名。
```c++
DWORD WINAPI ThreadFun(LPVOID pthread) {
lpthread temp = (lpthread)pthread;
temp->progress->SetPos(temp->pos);
while (temp->pos < 20) {
Sleep(temp->speed); // 设置速度
++(temp->pos); // 增加进度
temp->progress->SetPos(temp->pos); // 更新进度条位置
GlobalVar--;
if (temp->pos == 20)
temp->pos = 0;
}
return true;
}
```
6. 在启动按钮的处理函数中编写如下代码:
```c++
thread1.progress = &m_progress1; // 关联进度条
thread1.speed = 100; // 设置速度值为100
hThread1 = CreateThread(NULL, 0, ThreadFun, (LPVOID)&thread1, 0, NULL);
if (!hThread1) {
MessageBox(创建线程失败);
}
```
7. 在挂起按钮的处理函数中编写如下代码:
```c++
if(SuspendThread(hThread1)==-1)
{
MessageBox(挂起失败!进程可能已经死亡或未创建!);
return;
}
```
8. 在执行按钮的处理函数中编写如下代码:
```c++
if(ResumeThread(hThread1) == -1)
{
MessageBox(恢复线程失败!进程可能已经死亡或未创建!);
return ;
}
```
9. 在停止按钮的处理函数中编写如下代码:
```c++
if(TerminateThread(hThread1,0))
{
CloseHandle(hThread1);
} else {
MessageBox(终止线程失败!);
}
```
10. 为应用程序添加WM_TIMER消息,用于实时更新全局变量值到编辑框。