【问题标题】:How to create multithread logger in c++如何在 C++ 中创建多线程记录器
【发布时间】:2021-12-03 22:00:23
【问题描述】:

我想在c++ 中创建一个多线程记录器,它也可以从c 代码中调用。

这是在我的source.cpp 文件中:

#include <cstdlib>
#include <iostream>
#include <thread>
#include "source.h"
using namespace std;

#ifdef __cplusplus
extern "C" {
#endif
class thread_obj {
public:
    void operator()(float* x)
    {
        printf("value: %d", x);
    }
};

void log(float value)
{
    thread th1(thread_obj(), value);
    th1.join();
}

#ifdef __cplusplus
}
#endif

这是source.h:

#ifdef __cplusplus
extern "C" {
#endif
    void log(float value);
#ifdef __cplusplus
}
#endif

现在我想从C 文件中使用它,例如:log(myFloatValue);,当然还有包含的头文件。

但我遇到了一些奇怪的错误,例如:

Error   C2672   'invoke': no matching overloaded function found myproj C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread   43  
Error   C2893   Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Ty1 &&,_Types2 &&...) noexcept(<expr>)'  myproj C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread   39  
Error   C2780   'unknown-type std::invoke(_Callable &&) noexcept(<expr>)': expects 1 arguments - 2 provided hackatlon_0_0_1 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread  39  

我的问题是,我该怎么做,或者我该如何解决这些错误?

【问题讨论】:

  • 哪种语言,C 还是 C++?您的答案可能因语言而异。适当调整你的语言标签。
  • @ThomasMatthews 这是我想从 C 代码中调用的 C++ 代码。
  • 如果我没记错的话,我认为你不应该在课堂部分使用 extern "C"。 C++ 位应该对“C”完全隐藏。所以 void log(float value) 应该转发给一个内部类,但是那个类不应该被导出
  • 对于多线程部分,您可能需要一个消息队列,这些消息将由日志调用(生产者)填充,然后从日志线程(消费者)进行实际日志记录。如果你像现在这样产生一个线程然后加入它,那只是一个非常昂贵的同步调用。
  • @PepijnKramer 对,更不用说,你应该考虑足够的内存资源来进行缓冲。

标签: c++ c multithreading visual-studio


【解决方案1】:

您的代码存在多个问题:

  1. operator() 的参数应该是 float x 而不是 float*,因为这是您传递给线程的内容
  2. 您的日志函数与标准数学日志冲突。更改函数名称或将其放入不同的命名空间
  3. printf 使用格式说明符"%d"。它应该是"%f",因为输入是浮点数
  4. 您不需要为课程输入extern "C"。您正在避免仅对需要从 c 文件调用的 log 函数进行名称修改。

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多