简体   繁体   English

C中Logger线程的线程安全队列

[英]Thread-safe queue for Logger thread in C

So, I have a MMO game server listening for connections (up to 1100, hardcoded limit because of game design) and needing to log everything without blocking my main thread (which handles all the virtual-world logic), including but not limited to: what NPCs give to players, when a monster/player dies, every single chat message, when players level up, when players drop an item to the ground, etc. 因此,我有一个MMO游戏服务器,它监听连接(最多1100个,由于游戏设计而受到硬编码限制),并且需要记录所有内容而又不阻塞我的主线程(处理所有虚拟世界逻辑),包括但不限于: NPC给玩家的东西,怪物/玩家死亡时,每条聊天消息,玩家升级时,玩家将物品掉到地上时等等。

I get a thread from a pool for each connection, and each thread can log to a file at any time (it may actually never happen, but the server must be prepared enough to handle it appropriately). 我从每个连接的池中获得一个线程,并且每个线程可以随时登录到文件(它实际上可能永远不会发生,但是服务器必须准备充分以适当地处理它)。

I thought about an independent logging thread constantly checking an order queue, until it is not empty. 我想到了一个独立的日志记录线程,它会不断检查订单队列,直到它不为空。

while Game is Running
    Check the queue, if it's empty, sleep.
    File IO. Open plain-text file, log and gracefully close it.
    Repeat.

Is a linked list enough for organizing the queue and just protect it with a mutex like this? 链表是否足以组织队列并仅使用这样的互斥体对其进行保护?

LogThreadOrder Queue[1024];

LogThreadOrder *FirstThreadOrder;
int NumberOfOrders;

struct LogThreadOrder {
    char FileName[4096];
    char LogMessage[4096];
    LogThreadOrder* NextOrder;
};

void Log(const char* FileName, const char* LogMessage) {
    LogMutex.lock();

    ProtocolThreadOrder* Order = Queue[NumberOfOrders++];
    Order->NextOrder = FirstThreadOrder;
    FirstThreadOrder = Order;

    LogMutex.release();

}


int LogThreadLoop() {
    // Loop through Queue until its empty.
}

So, my question is: 所以,我的问题是:

  • Is this a smart design? 这是一个聪明的设计吗?

  • Is it thread-safe? 它是线程安全的吗?

  • Is there any better way of accomplishing what I'm trying to do? 有什么更好的方法可以完成我想做的事情?

  • Would it be better/more-efficient to have multiple logger threads and multiple queues? 拥有多个记录器线程和多个队列会更好/更有效吗?

Your pseudocode could be made to work, but it's difficult in C and mutex synchronization is inefficient. 可以使您的伪代码正常工作,但是在C语言中这很困难,并且互斥锁同步效率很低。 In my experience it's always better to use existing, well-established, asynchronous inter-process communication mechanisms between threads like named pipes . 以我的经验,在诸如命名管道之类的线程之间使用现有的,建立良好的异步进程间通信机制总是更好。 Even then there are many pitfalls and when dependencies aren't a problem using something like ZeroMQ might be the best idea. 即使这样,仍然存在很多陷阱,当使用ZeroMQ之类的依赖关系没有问题时,这可能是最好的主意。 Specifically something like this . 特别是像这样 I don't think having multiple threads is a good idea, as file you want to write to will be a contention point. 我认为拥有多个线程不是一个好主意,因为要写入的文件将成为争用点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM