#2
rjsp2023-05-25 10:23
|
程序代码:
#include <windows.h>
#include <process.h>
#include<iostream>
#include<stdio.h>
unsigned WINAPI threadInc(void* arg);
unsigned WINAPI threadDes(void* arg);
HANDLE hEvent;
int main(int argc, char* argv[])
{
HANDLE Handles[2]{};
int i;
hEvent = CreateEvent(NULL, FALSE, TRUE, NULL);
Handles[0] = (HANDLE)_beginthreadex(NULL, 0, threadA, NULL, 0,
NULL);
Handles[1] = (HANDLE)_beginthreadex(NULL, 0, threadB, NULL, 0,
NULL);
WaitForMultipleObjects(2, Handles, TRUE, INFINITE);
CloseHandle(hEvent);
system("pause");
return 0;
}
unsigned WINAPI threadA(void* arg)
{
for (int j=0;j<2;j++)
{
int i;
std::cout << "我是猪" << std::endl;
WaitForSingleObject(hEvent, INFINITE);
for (int i = 0; i < 2; i++)
{
std::cout << "我是猪22" << std::endl;
}
SetEvent(hEvent);
}
return 0;
}
unsigned WINAPI threadB(void* arg)
{
for (int j=0;j<2;j++)
{
int i;
std::cout << "woshizhu" << std::endl;
WaitForSingleObject(hEvent, INFINITE);
for (int i = 0; i < 2; i++)
{
std::cout << "woshizhu33" << std::endl;
}
SetEvent(hEvent);
}
return 0;
}
遇到了4个问题,
1.将hEvent 设置为有信号状态,随机进入线程A,打印“我是x”,接下来有没有可能连续打印两次中文“我是x22”呢?
2.再连续打印两次中文“我是X22"后,SetEvent,然后,因为自己发出的SetEvent不作用于自己,所以会进入线程B,那这个时候会跳到waitfor那一行呢?还是会跳到线程B里的打印英文”woshix“那一行(后面没有33)
3.按照2的逻辑,线程A结束后不会再次执行线程A,但为什么会有这样的结果,连续打印了两次线程A
woshizhu
woshizhu33
woshizhu33
woshizhu
woshizhu33
woshizhu33
只有本站会员才能查看附件,请 登录
4.为什么打印结果有一行空着呢?我只写了个换行,是打印结果后换行,而不是让它换整个空行
只有本站会员才能查看附件,请 登录
[此贴子已经被作者于2023-5-25 10:02编辑过]