将数据打印到文件 [英] To print data to a file
问题描述
我已经重载<<
运算符,以便它写入文件和控制台。我已经为同一个函数创建了8个线程,我想输出
hello
hi
如果我在无限循环中运行这个线程例程,文件中的o / p是
hello
hi
hello
hi
hello
hi
ello
i
hello
hi
hello
hi
i
hello
p>
这没有模式。问题是什么?我可以在控制台上正确打印,但不能打印到文件中。
创建队列并写入。以所需的粒度排队队列 - 例如一行(我猜这是你想从你的例子)。
像:
CRITICAL_SECTION cs;
list< string> _队列;
void Write(string line)
{
EnterCriticalSection(& cs);
_queue.push_back(line);
LeaveCriticalSection(& cs);
}
ThreadProc()
{
while(!_shouldStop)
{
Dequeue
Sleep(100);
}
}
void Dequeue()
{
EnterCriticalSection(& cs);
if(!_queueIsEmpty())
{
string line = _queue.front();
_queue.pop_front();
stream<<线;
}
LeaveCriticalSection(& cs);
}
这不是C代码 - 这只是一个例子,有很多
- 您的粒度可能会有所不同,我在这里使用了
- 您可能想要使用dequeue<>或一些类似的FIFO结构
- 您可能想要
WaitForSingleObject()
而不是Sleep()
-ing可以更好地控制您要停止的情况 - 为这些东西创建单例对象,它在哪里你需要它(我想你正在创建某种记录设施?)
I have overloaded <<
operator such that it write to file and also on the console. I have created 8 threads to the same function, and I want to output
hello
hi
If I run this thread routine in an infinite loop the o/p in the file is
hello
hi
hello
hi
hello
hi
ello
i
hello
hi
hello
hi
llo
i
hello
hi
This has no pattern. What is the problem? I am able to print it properly on console but not into a file.
Create a queue and write to it. Dequeue queue in desired granularity - one line for example (I guess that that's what you want from your example).
Something like:
CRITICAL_SECTION cs;
list<string> _queue;
void Write(string line)
{
EnterCriticalSection(&cs);
_queue.push_back(line);
LeaveCriticalSection(&cs);
}
ThreadProc()
{
while (!_shouldStop)
{
Dequeue();
Sleep(100);
}
}
void Dequeue()
{
EnterCriticalSection(&cs);
if (!_queueIsEmpty())
{
string line=_queue.front();
_queue.pop_front();
stream << line;
}
LeaveCriticalSection(&cs);
}
This is not C code - this is just a example, there are lot's of other things to have in mind, just to name few of them:
- your granularity might vary, I used line here
- you might want to use dequeue<> or some similar FIFO structure
- you might want to
WaitForSingleObject()
instead ofSleep()
-ing to have better control for cases when you want to stop - create singleton object for the stuff and use it where you need it (I guess that you are creating some kind of logging facility?)
这篇关于将数据打印到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!