求哪位好心人,把这个改成一个线程负责打印,一个线程负责定时,1秒到了,终止打印,看总共打印了多少行
#include <stdio.h>#include <Windows.h>#include <time.h>#include <process.h>unsigned __stdcall Print(void *params){ int i = 0; clock_t start; start = clock(); while ((double)(clock() - start) / CLOCKS_PER_SEC < 1.0) { printf("%d\n", ++i); } return 0;}int main(){ HANDLE hThread; unsigned threadId; hThread = (HANDLE)_beginthreadex(NULL, 0, &Print, NULL, 0, &threadId); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); system("pause");}volatile LONG g_bCon;void printThread(void* pArg){ int i = 0; while(g_bCon){ printf("%d\n",i++); }}void countThread(void* pArg){ _beginthread(printThread,0,0); Sleep(1000); g_bCon = 0;}int main(int argc, char* argv[]){ g_bCon = 1; _beginthread(countThread,0,0); return 0;}
[解决办法]
#include <stdio.h>#include <Windows.h>#include <time.h>#include <process.h>int g_start = -1;unsigned __stdcall Print(void *params){ int i = 0; clock_t start; start = clock(); while(g_start == -1) sleep(1); while (g_start == 0) / CLOCKS_PER_SEC < 1.0) { printf("%d\n", ++i); } return 0;}unsigned __stdcall Control(void *params){ int i = 0; clock_t start; start = clock(); g_start == 0; sleep(1000); g_start ==-1 return 0;}int main(){ HANDLE hThread; unsigned threadId; hThread = (HANDLE)_beginthreadex(NULL, 0, &Print, NULL, 0, &threadId); HANDLE hThread1; unsigned threadId1; hThread1 = (HANDLE)_beginthreadex(NULL, 0, &Control, NULL, 0, &threadId1); WaitForSingleObject(hThread, INFINITE); WaitForSingleObject(hThread1, INFINITE); CloseHandle(hThread); CloseHandle(hThread1); system("pause");}