Search code examples
c++qtqthreadcritical-sectionqmutex

Handling with Critical Sections in Qt


I've searched a lot for an answer to this question, but it seems there isn't any.

I'm using Qt 5.2.0 to make a TCP client with winsocks2. The language in use is C++. To make the connection loop (where I call send() and write()) I'm using QThread (that can be read here http://qt-project.org/doc/qt-4.8/qthread.html), it's worked well so far, but I want to be sure that there is no context switching when my program is writing or reading something. So I've thought that critical sections would be the right way to do it, but in my searches on the Internet I haven't found any way to do it and even in the Qt official documentation there is no reference to critical section.

Then here is my question: Is there some way to use critical sections in Qt? Do I need put a mutex in the section I want avoid context switching and put mutexes in other places? If affirmative, in which parts should I put these mutexes?

I'm sorry for my English. Thanks in advance.

If there is something more that I can inform, please tell me.

Murilo G. K.


Solution

  • Then here is my question: Is there some way to use critical sections in Qt? Do I need put a mutex in the section I want avoid context switching

    What you seem to be indicating is kernel level critical sections, not application critical sections which only deal with concurrent execution. Kernel level critical sections are in kernel mode only and have nothing to do with user applications. Context switching is a kernel level idea, not user mode.

    If you are asking about processor affinity, you have to use OS specific commands to set that. Qt does not abstract processor affinity.. This is the only way to be certain that your process will not jump between cores when it is scheduled.

    http://msdn.microsoft.com/en-us/library/windows/desktop/ms686247%28v=vs.85%29.aspx

    NOTE: There are very few situations where these functions are actually useful. Modern schedulers already want to reschedule a given thread on the same core it was running before to minimize cache misses.

    If you are asking about concurrent access to same data structures by multiple threads, then QMutex and similar are what you are looking for.