std :: lock_guard与可变参数模板

时间:2019-03-05 22:55:08

标签: c++ thread-safety variadic-templates

[不必通过链接来理解问题]。

我结合了this answer中单例模式的实现和this other answer的同步文件写入。

然后我想看看SynchronizedFile的接口是否可以提供可变参数的模板化write方法,但是我不知道如何将其与std::lock_guard正确组合。 / p>

下面是一个无效示例。在这种情况下,它是行不通的,因为(我认为)这两个线程设法以非同步方式将内容泵入缓冲区i_buf中,导致LOGFILE.txt出现乱码。

如果我将std::lock_guard放在write的通用模板中,则程序不会停止。

#include <iostream>
#include <mutex>
#include <sstream>
#include <fstream>
#include <string>
#include <memory>
#include <thread>

static const int N_LOOP_LENGTH{10};

// This class manages a log file and provides write method(s)
// that allow passing a variable number of parameters of different
// types to be written to the file in a line and separated by commas.
class SynchronizedFile {
public:
    static SynchronizedFile& getInstance()
    {
        static SynchronizedFile instance;
        return instance;
    }

private:
    std::ostringstream i_buf;
    std::ofstream i_fout;
    std::mutex _writerMutex;

    SynchronizedFile () {
        i_fout.open("LOGFILE.txt", std::ofstream::out);
    }

public:
    SynchronizedFile(SynchronizedFile const&) = delete;
    void operator=(SynchronizedFile const&)   = delete;

    template<typename First, typename... Rest>
    void write(First param1, Rest...param)
    {
        i_buf << param1 << ", ";
        write(param...);
    }

    void write()
    {
        std::lock_guard<std::mutex> lock(_writerMutex);
        i_fout << i_buf.str() << std::endl;
        i_buf.str("");
        i_buf.clear();
    }
};

// This is just some class that is using the SynchronizedFile class
// to write stuff to the log file.
class Writer {
public:
    Writer (SynchronizedFile& sf, const std::string& prefix) 
        : syncedFile(sf), prefix(prefix) {}

    void someFunctionThatWritesToFile () {
        syncedFile.write(prefix, "AAAAA", 4343, "BBBBB", 0.2345435, "GGGGGG");
    }
private:
    SynchronizedFile& syncedFile;
    std::string prefix;
};

void thread_method()
{
  SynchronizedFile &my_file1 = SynchronizedFile::getInstance();
  Writer writer1(my_file1, "Writer 1:");
  for (int i = 0; i < N_LOOP_LENGTH; ++ i)
    writer1.someFunctionThatWritesToFile();
}

int main()
{
  std::thread t(thread_method);

  SynchronizedFile &my_file2 = SynchronizedFile::getInstance();
  Writer writer2(my_file2, "Writer 2:");
  for (int i = 0; i < N_LOOP_LENGTH; ++i)
    writer2.someFunctionThatWritesToFile();

  t.join();
  std::cout << "Done" << std::endl;
  return 0;
}

我如何成功地结合这三个想法?

1 个答案:

答案 0 :(得分:2)

程序死锁是因为KEY_STRING = '''_____GP D_____''' text = """INFO:modules.gp.helpers.parameter_getter:_____GP D_____ {'from_time': '2017-07-12 19:57', 'to_time': '2017-07-12 20:57', 'consig_number': 'dup1', 'text': 'r155', 'mobile': None, 'email': None} ERROR:modules.common.actionexception:ActionError: [{'other': 'your request already crossed threshold time'}] {'from_time': '2016-07-12 16:57', 'to_time': '2016-07-12 22:57', 'consig_number': 'dup2', 'text': 'r15', 'mobile': None, 'email': None}""" lines = text.split("\n") # load log text into a list. # for loading from log would be more like # with open("/var/log/syslog.log", 'r') as f: # lines = f.readlines() # set "gate" flag to False flag = False for loop in lines: line = loop.strip() if flag: # "gate" opened # depends how's the dictionary streamed to log # you could use json.loads(line), but if it is not sent to log with json.dumps than you have pythonic dictinary and use # literal_eval to load that dictionary to a variable # .. a target_json = literal_eval(line) print json.dumps(target_json, indent=4) if KEY_STRING in line: flag = True # KEY_STRING found open "gate" else: flag = False # close "gate" ~ 在保持锁的状态下递归调用自身。

在写入数据之后但在调用{ "consig_number": "dup1", "text": "r155", "email": null, "mobile": null, "to_time": "2017-07-12 20:57", "from_time": "2017-07-12 19:57" 之前使用std::recursive_mutex 或释放锁。 E:解锁并不能完成任务,我没有想到……

E:或者锁定一次并遵照另一个私有方法进行写入。

write