Click here to Skip to main content
15,887,971 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Below is my code snippet for mutual exclusion of execution by multi-threads:
C#
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";
    }
}


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?
Posted
Comments
Sergey Alexandrovich Kryukov 4-Aug-15 0:50am    
Where is the declaration and initialization of mutexLog. What do you mean by "not working"? How "keeps being displayed" related to the lock?
—SA
Ashish Tyagi 40 4-Aug-15 19:24pm    
openLogFile() call is returning NULL, fix that first.
Stan Huang 4-Aug-15 19:38pm    
I missed it and what you said is right.

1 solution

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
 
Share this answer
 
Comments
Stan Huang 4-Aug-15 5:45am    
What you said is right: openLogFile() is the trouble maker and I figured it out. This bug has nothing to do with locking issue among threads.
The misunderstanding came from that I think since it failed to open, it must due to the racing to open file among threads.
I still think locking is necessary before open logging file to prevent to open a file while it's still not closed.
Sergey Alexandrovich Kryukov 4-Aug-15 10:19am    
Great.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900