2月初的时候接到一个需求,简单点说就是做个动画。
运用多线程的技术,当动画启动的时候,不影响其他画面的表示和押键响应。
A 线程启动后,在某个阶段启动了B线程。
A这里使用main()函数,B这里使用让动画'动'起来的线程animation,那么可以这么做,直接看代码。
#include <stdio.h>
#include <windows.h>
DWORD WINAPI animation();
int main()
{
char endFlag = 0;
CreateThread(
NULL // default security attributes
,0 // use default stack size
,animation // thread function
,NULL // argument to thread function
,0 // use default creation flags
,NULL); // returns the thread identifier
while (1){
int i;
printf ("A还在运行中!!!\n\n\n");
for(i = 0; i < 200000000; i++){
;
}
}
return 0;
}
DWORD WINAPI animation()
{
int pic[4] = {1,2,3,4};
int i = 0;
printf ("在这里进行图片切换!\n");
while (1){
int j = 0;
if (i < 4){
int currentPic = pic[i];
printf ("当前是第%d帧\n",currentPic);
i++;
for(j = 0; j < 200000000; j++){
;
}
} else if (i >= 4) {
i = 0;
}
}
}
在main()里面有一个for(i = 0; i < 200000000; i++){;},在真实的项目中,这里的大括号中多用来进行押键的回调函数,这样主线程永远不会退出。在animation函数中,有一个for(j = 0; j < 200000000;j++){;},真实项目中,这里一般是计算你动画要动多快的时间,使用sleep(时间间隔);来确定。
新创建的线程什么时候结束?线程间怎么进行通信?线程内部是否能结束自己,外部呢?这些问题接下来研究。