怎么来lock_guard不起作用? [英] How come lock_guard doesn't work?

查看:276
本文介绍了怎么来lock_guard不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我通过多线程互斥执行的代码段:

Below is my code snippet for mutual exclusion of execution by multi-threads:

void logMsg (char *msg)
{
    FILE * pFile;
    try {
        lock_guard<mutex> lock(mutexLog);
        pFile = openLogFile();
        if (pFile !=NULL)
        {
            fprintf (pFile, "%s", msg);
            fclose (pFile);
        }
        else
            printf ("failed to log %s in logMsg()\n", msg);
    } catch (std::exception& e) {
        std::cerr << "logMsg(): " << e.what() << "\n";
    }
}





我通过多个线程到处调用logMsg()。 Lock_guard似乎无法正常工作,因为未能记录....的消息不断显示。怎么会?我的代码有什么问题吗?



I called logMsg() everywhere by more than one thread. Lock_guard seems not working because message of "failed to log ...." keeps being displayed. How come? Any wrong with my codes?

推荐答案

请看我对这个问题的评论。如果没有任何意义,因为问题1)根本不是问题,2)与锁定无关。

你的 pFile value为null,就是这样。看看 openLogFile()是什么,使用调试器。这就是解决方案。



对于日志记录,在两个或多个线程之间共享某些资源时使用它。如果不这样做,则不需要锁定。我有一种印象,你不知道它用于什么。你不应该写一行你不完全理解的。因此,请阅读:

https://en.wikipedia.org/wiki/Mutual_exclusion [ ^ ],

http://en.cppreference.com/w/cpp/thread/lock_guard [ ^ ]。



-SA
Please see my comment to the question. If does not make any sense, because the "problem" 1) is not a problem at all, 2) is not related to locking in any way.
Your pFile value is null, that's all. See what openLogFile() does, use the debugger. That's the solution.

As to the logging, it is used when some resource is shared between two or more threads. If you don't do it, you don't need locking. I have an impression that you don't have a clue what is it used for. You should not write a single line you don't perfectly understand. So, please read:
https://en.wikipedia.org/wiki/Mutual_exclusion[^],
http://en.cppreference.com/w/cpp/thread/lock_guard[^].

—SA


这篇关于怎么来lock_guard不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆