人搓,没有看懂别人的帖子

bsnry 2012-04-27 06:02:09
一道输入输出线程互斥的题

羞愧,人搓,没有成功实现。


问题描述:

在控制台下输入的时候,阻止输出线程,直到输入一行字符串后,完成后再次开启输出线程。

也就是说,当输入'\n'的时候,那么就又开始打印了。

原帖子:
http://topic.csdn.net/u/20120427/10/23a2316b-7706-4813-8363-73e4c1179aee.html?43281




以下是我提供的代码版本,是不能满足题意的。因为当输出线程运行的的时候,无法输入。




#include "stdafx.h"

#include <iostream>
#include <windows.h>
#include <process.h>



using std::cout;
using std::endl;


static char c;

unsigned _stdcall threadFun1(void*)
{
while(1)
{
c=getchar();

}
return 0;
}


unsigned int _stdcall threadFun2(void*)
{

while(1)
{
if(c=='\n')
{
//打印

cout<<"hello"<<endl;

}
}
return 0;
}







int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1,hThread2;


hThread1=(HANDLE)_beginthreadex(NULL,0,threadFun1,NULL,0,NULL);

hThread2=(HANDLE)_beginthreadex(NULL,0,threadFun2,NULL,0,NULL);

WaitForSingleObject(hThread1,-1);

WaitForSingleObject(hThread2,-1);

CloseHandle(hThread1);
CloseHandle(hThread2);

return 0;
}

...全文
185 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
bsnry 2012-04-27
  • 打赏
  • 举报
回复

我几个疑问,能帮忙解答一下吗?
while (true)
{
CSHelper cs(g_cs);
cout << "Kom" << endl;
::SwitchToThread();
}
这里为什么要切换线程? 这种切换线程会达到什么效果啊。 什么时候才会用这个函数呢
谢谢了啊。
muyelian 2012-04-27
  • 打赏
  • 举报
回复
楼主试试这个
#include <Windows.h>
#include <process.h>
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;

CRITICAL_SECTION g_cs;

class CSHelper
{
public:
CSHelper(CRITICAL_SECTION & cs) :
m_cs(cs)
{
::EnterCriticalSection(&m_cs);
}

~CSHelper(void)
{
::LeaveCriticalSection(&m_cs);
}

private:
CRITICAL_SECTION & m_cs;
};

unsigned __stdcall InputThread(void * data)
{
while (true)
{
if (_kbhit())
{
CSHelper cs(g_cs);
string s;
getline(cin, s);
cout << s << endl;
}
}
}

unsigned __stdcall OutputThread(void * data)
{
while (true)
{
CSHelper cs(g_cs);
cout << "Kom" << endl;
::SwitchToThread();
}
}

int main()
{
::InitializeCriticalSection(&g_cs);
HANDLE hInputThread = (HANDLE)::_beginthreadex(NULL, 0, InputThread, NULL, 0, NULL);
HANDLE hOutputThread = (HANDLE)::_beginthreadex(NULL, 0, OutputThread, NULL, 0, NULL);

::WaitForSingleObject(hInputThread, INFINITE);
::WaitForSingleObject(hOutputThread, INFINITE);

::CloseHandle(hInputThread);
::CloseHandle(hOutputThread);
::DeleteCriticalSection(&g_cs);
return 0;
}

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧