64,648
社区成员
发帖
与我相关
我的任务
分享
一道输入输出线程互斥的题
羞愧,人搓,没有成功实现。
问题描述:
在控制台下输入的时候,阻止输出线程,直到输入一行字符串后,完成后再次开启输出线程。
也就是说,当输入'\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;
}
我几个疑问,能帮忙解答一下吗?
while (true)
{
CSHelper cs(g_cs);
cout << "Kom" << endl;
::SwitchToThread();
}
这里为什么要切换线程? 这种切换线程会达到什么效果啊。 什么时候才会用这个函数呢
谢谢了啊。
#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;
}