#include <windows.h> //包含頭文件#include <stdio.h>DWORD WINAPI myfun1( //聲明線程函數(shù)LPVOID lpParameter );const int stop=1; //stop 為一const int go_on=2; //開始為2int record=2; static HANDLE hmutex;int a=0; //定義全局變量aint main(){ HANDLE h1; //定義線程句柄h1=::CreateThread(NULL,0,myfun1,NULL,0,NULL);printf("haha\n");//創(chuàng)建線程1::CloseHandle(h1); Sleep(1000);//關(guān)閉線程句柄對象 return 0;}DWORD WINAPI myfun1(LPVOID lpParameter) //線程函數(shù)1{ while(1){::WaitForSingleObject(hmutex,INFINITE); //請求事件對象//變量自加a++; //線程睡眠1秒printf("qiubai\n");::ReleaseMutex(hmutex); if(a>0)break;//釋放互斥對象句柄}return 0; //線程}
1 回答

慕容708150
TA貢獻1831條經(jīng)驗 獲得超4個贊
你應(yīng)該建立兩個進程, 這樣才可以觀察, 還有你的 haha 是在 main 函數(shù)里面, 只執(zhí)行一次, 不會輸出多次, qiubai, 在進程中, 但是 if (a>0) 也就是執(zhí)行一次之后這個進程雖然沒有關(guān)閉但是, 已經(jīng)不可能進入輸出的程序了.
#include <windows.h> #include <stdio.h> DWORD WINAPI myfun1( LPVOID lpParameter); DWORD WINAPI myfun2( LPVOID lpParameter); static HANDLE hmutex, hmutex2; int main() { HANDLE h1; h1=::CreateThread(NULL,0,myfun1,NULL,0,NULL); HANDLE h2; h2=::CreateThread(NULL,0,myfun2,NULL,0,NULL); printf ( "Start:\n" ); Sleep(5000); ::CloseHandle(h1); ::CloseHandle(h2); return 0; } DWORD WINAPI myfun1( LPVOID lpParameter) { int a = 0; while (1) { ::WaitForSingleObject(hmutex,INFINITE); a++; printf ( "qiubai\n" ); ::ReleaseMutex(hmutex); Sleep(200); if (a > 15) break ; } return 0; } DWORD WINAPI myfun2( LPVOID lpParameter) { int b = 0; while (1) { ::WaitForSingleObject(hmutex2,INFINITE); b++; printf ( "haha\n" ); ::ReleaseMutex(hmutex2); Sleep(300); if (b > 10) break ; } return 0; } |
- 1 回答
- 0 關(guān)注
- 76 瀏覽
添加回答
舉報
0/150
提交
取消