先來說說作者在什麼狀況下寫出這種的範例
作者是看到某一牌手機上,當簡訊已滿時,會閃爍著信的圖案,而又不影響手機其它的動作。
所以就想在console mode下實現出類似的功能
主要是利用兩個執行緒,一個是主執行緒(main thread),而另一個是所謂的worker執行緒
主執行緒負責輸入的動作,worker執行緒負責規律或週期性的動作,且受主執行緒的控制
此範例感覺網友Franz的幫助,本來是以waitable timer配合執行緒的方式來撰寫以上的功能
但出現小部份的問題,請教Franz之後得到解決的方案,但仍未獲得完全的解決。
以下程式的流程:
有兩個thread,一為main thread,另一個為worker thread
main thread負責輸入的動作
當輸入為1(ON)時,則每隔1秒發出"噹"的聲音,即為MessageBeep(0)
當輸入為0(OFF)時,則不發出聲音
當輸入為2(EXIT)時,則結束執行
發出"噹"的聲音,由worker thread負責。
若有什麼問題可以聯絡作者
Franz與作者修改後,所得到的程式碼如下:
#include <stdio.h>
#include <windows.h>
volatile int iInit = 0;
volatile enum STATE { EXIT,OFF,ON } bMessageFulled = OFF;
DWORD WINAPI ThreadFunc( LPVOID lpParam )
{
int iOldTick, iCurrentTick;
iOldTick = 0;
while (1) {
if (bMessageFulled == ON) {
iCurrentTick = GetTickCount();
if (bMessageFulled == ON && iInit == 1) {
iOldTick = iCurrentTick - 1000;
iInit = 0;
}
if (iCurrentTick - iOldTick >= 1000) {
MessageBeep(0);
printf("%d\n", iCurrentTick);
iOldTick = iCurrentTick;
}
}
}
return 0;
}
int main(int argc, char *argv[])
{
DWORD dwThreadId;
HANDLE hThread;
char szMsg[80];
int iControl;
hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadFunc, // thread function
0, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
if (hThread == NULL)
{
wsprintf(szMsg, "CreateThread failed.");
printf("%s", szMsg);
}
else
{
printf("Sound=> ON(1) OFF(0) EXIT(2) : ");
do {
scanf("%ud",&iControl);
switch (iControl) {
case 0:
bMessageFulled = OFF;
break;
case 1:
bMessageFulled = ON;
break;
}
if (iControl == 2)
break;
if (bMessageFulled == OFF)
iInit = 1;
} while (1);
CloseHandle( hThread );
}
return 0;
}
Written By James On 2006/12/05