#include <windows.h> //包含头文件#include <stdio.h>DWORD WINAPI myfun1( //声明线程函数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");//创建线程1::CloseHandle(h1); Sleep(1000);//关闭线程句柄对象 return 0;}DWORD WINAPI myfun1(LPVOID lpParameter) //线程函数1{ while(1){::WaitForSingleObject(hmutex,INFINITE); //请求事件对象//变量自加a++; //线程睡眠1秒printf("qiubai\n");::ReleaseMutex(hmutex); if(a>0)break;//释放互斥对象句柄}return 0; //线程}
1 回答
慕容708150
TA贡献1831条经验 获得超4个赞
你应该建立两个进程, 这样才可以观察, 还有你的 haha 是在 main 函数里面, 只执行一次, 不会输出多次, qiubai, 在进程中, 但是 if (a>0) 也就是执行一次之后这个进程虽然没有关闭但是, 已经不可能进入输出的程序了.
#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 关注
- 90 浏览
添加回答
举报
0/150
提交
取消
