3

什么是创建我自己的最简单的方法,std::cerr以便它是逐行线程安全的。

我最好寻找代码来做到这一点。

我需要的是,当我在控制台上实际看到一个线程生成的a line of output(以 结尾)时(并且不与其他线程的输出混合)。std::endlas a line of output


解决方案std::cerr比cstdio 慢得多我更喜欢在其构造函数获取线程安全锁并且析构函数释放它fprintf(stderr, "The message")的类内部使用。CriticalSectionLocker

4

5 回答 5

7

如果可用,osyncstream (C++20) 可以解决这个问题:

#include <syncstream> // C++20

std::osyncstream tout(std::cout);
std::osyncstream terr(std::cerr);

如果上述功能不可用,这里有一个包含两个用于线程安全写入std::cout和的宏的插入头文件std::cerr(必须共享一个互斥锁以避免输出交错)。这些基于其他两个 答案,但我进行了一些更改,以便轻松放入现有代码库。这适用于 C++11 及更高版本。

我已经在 4 核处理器上使用 4 个线程对此进行了测试,每个线程每秒写入 25,000 行tout并偶尔输出到terr,它解决了输出交错问题。与基于结构的解决方案不同,在放入此头文件时,我的应用程序没有明显的性能损失。我能想到的唯一缺点是,由于这依赖于宏,因此不能将它们放入命名空间中。

线程流.h

#ifndef THREADSTREAM
#define THREADSTREAM

#include <iostream>
#include <sstream>
#include <mutex>

#define terr ThreadStream(std::cerr)
#define tout ThreadStream(std::cout)

/**
 * Thread-safe std::ostream class.
 *
 * Usage:
 *    tout << "Hello world!" << std::endl;
 *    terr << "Hello world!" << std::endl;
 */
class ThreadStream : public std::ostringstream
{
    public:
        ThreadStream(std::ostream& os) : os_(os)
        {
            // copyfmt causes odd problems with lost output
            // probably some specific flag
//            copyfmt(os);
            // copy whatever properties are relevant
            imbue(os.getloc());
            precision(os.precision());
            width(os.width());
            setf(std::ios::fixed, std::ios::floatfield);
        }

        ~ThreadStream()
        {
            std::lock_guard<std::mutex> guard(_mutex_threadstream);
            os_ << this->str();
        }

    private:
        static std::mutex _mutex_threadstream;
        std::ostream& os_;
};

std::mutex ThreadStream::_mutex_threadstream{};

#endif

测试.cc

#include <thread>
#include <vector>
#include <iomanip>
#include "threadstream.h"

void test(const unsigned int threadNumber)
{
    tout << "Thread " << threadNumber << ": launched" << std::endl;
}

int main()
{
    std::locale mylocale(""); // get global locale
    std::cerr.imbue(mylocale); // imbue global locale
    std::ios_base::sync_with_stdio(false); // disable synch with stdio (enables input buffering)

    std::cout << std::fixed << std::setw(4) << std::setprecision(5);
    std::cerr << std::fixed << std::setw(2) << std::setprecision(2);

    std::vector<std::thread> threads;

    for (unsigned int threadNumber = 0; threadNumber < 16; threadNumber++)
    {
        std::thread t(test, threadNumber);
        threads.push_back(std::move(t));
    }

    for (std::thread& t : threads)
    {
        if (t.joinable())
        {
            t.join();
        }
    }

    terr << std::endl << "Main: " << "Test completed." << std::endl;

    return 0;
}

编译

g++ -g -O2 -Wall -c -o test.o test.cc
g++ -o test test.o -pthread

输出

./test
Thread 0: launched
Thread 4: launched
Thread 3: launched
Thread 1: launched
Thread 2: launched
Thread 6: launched
Thread 5: launched
Thread 7: launched
Thread 8: launched
Thread 9: launched
Thread 10: launched
Thread 11: launched
Thread 12: launched
Thread 13: launched
Thread 14: launched
Thread 15: launched

Main: Test completed.
于 2018-11-13T19:22:32.253 回答
3

这是我在某个时候设计的基于线程安全的行的日志记录解决方案。它使用 boost mutex 来保证线程安全。它比必要的稍微复杂一些,因为您可以插入输出策略(应该转到文件、stderr 还是其他地方?):

记录器.h:

#ifndef LOGGER_20080723_H_
#define LOGGER_20080723_H_

#include <boost/thread/mutex.hpp>
#include <iostream>
#include <cassert>
#include <sstream>
#include <ctime>
#include <ostream>

namespace logger {
    namespace detail {

        template<class Ch, class Tr, class A>
        class no_output {
        private:
            struct null_buffer {
                template<class T>
                null_buffer &operator<<(const T &) {
                    return *this;
                }
            };
        public:
            typedef null_buffer stream_buffer;

        public:
            void operator()(const stream_buffer &) {
            }
        };

        template<class Ch, class Tr, class A>
        class output_to_clog {
        public:
            typedef std::basic_ostringstream<Ch, Tr, A> stream_buffer;
        public:
            void operator()(const stream_buffer &s) {
                static boost::mutex mutex;
                boost::mutex::scoped_lock lock(mutex);
                std::clog << now() << ": " << s.str() << std::endl;
            }

        private:
            static std::string now() {
                char buf[64];
                const time_t tm = time(0);  
                strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", localtime(&tm));
                return buf;
            }

        };

        template<template <class Ch, class Tr, class A> class OutputPolicy, class Ch = char, class Tr = std::char_traits<Ch>, class A = std::allocator<Ch> >
        class logger {
            typedef OutputPolicy<Ch, Tr, A> output_policy;
        public:
            ~logger() {
                output_policy()(m_SS);
            }
        public:
            template<class T>
            logger &operator<<(const T &x) {
                m_SS << x;
                return *this;
            }
        private:
            typename output_policy::stream_buffer m_SS;
        };
    }

    class log : public detail::logger<detail::output_to_clog> {
    };
}

#endif

用法如下所示:

logger::log() << "this is a test" << 1234 << "testing";

请注意缺少 a '\n'std::endl因为它是隐含的。内容被缓冲,然后使用模板指定的策略自动输出。此实现还在行前加上时间戳,因为它用于记录目的。该no_output策略是严格可选的,当我想禁用日志记录时使用它。

于 2010-12-15T22:08:28.660 回答
2

这:

#define myerr(e) {CiriticalSectionLocker crit; std::cerr << e << std::endl;}

适用于大多数编译器的常见情况myerr("ERR: " << message << number)

于 2010-12-15T05:01:14.977 回答
2

为什么不直接创建一个锁定类并在任何你想做线程安全 IO 的地方使用它呢?

class LockIO
{
    static pthread_mutex_t *mutex;  
public:
    LockIO() { pthread_mutex_lock( mutex ); }
    ~LockIO() { pthread_mutex_unlock( mutex ); }
};

static pthread_mutex_t* getMutex()
{
    pthread_mutex_t *mutex = new pthread_mutex_t;
    pthread_mutex_init( mutex, NULL );
    return mutex;
}
pthread_mutex_t* LockIO::mutex = getMutex();

然后你把你想要的任何 IO 放在一个块中:

std::cout <<"X is " <<x <<std::endl;

变成:

{
    LockIO lock;
    std::cout <<"X is " <<x <<std::endl;
}
于 2013-03-06T00:19:41.427 回答
1

对 unixman 评论中方法的改进(实际上并不适合评论)。

#define LOCKED_ERR \
    if(ErrCriticalSectionLocker crit = ErrCriticalSectionLocker()); \
    else std::cerr

哪个可以像

LOCKED_ERR << "ERR: " << message << endl;

如果 ErrCriticalSectionLocker 被仔细实施。

但是,我个人更喜欢肯的建议。

于 2010-12-15T06:45:04.717 回答