Using multithreaded and critical partitions - C ++

I am a bit confused about the proper use of critical sections in multi-threaded applications. There are several objects in my application (some circular buffers and a serial port object) that are shared between threads. Should access to these objects always be in critical sections or only at certain times? I suspect only at a certain time, because when I tried to wrap each use with EnterCriticalSection/ LeaveCriticalSection, I was faced with what seemed to be a deadlock condition. Any insight you might appreciate. Thank.

+3
source share
2 answers

If you share a resource by threads, and some of these threads read and others write, then it should always be protected.

It is hard to give more advice without knowing more about your code, but here are some general points to keep in mind.

1) Critical sections protect resources, not processes.

2) Enter / leave critical sections in the same order for all threads. If stream A enters Foo, then it enters Bar, then stream B must enter Foo and Bar in the same order. If you do not, you can create a race.

3) Input and care must be carried out in the reverse order. For example, since you entered Foo and then entered Bar, you must leave Bar before leaving Foo. If you do not, you can create a dead end.

4) . Foo, Bar, Foo , Bar. . , Foo, Bar, :

  Enter Foo
  Use Foo
  Leave Foo
  Enter Bar
  Use Bar
  Leave Bar

5) 99,9% 0,1% , . , . , , , .

6) . , . "", .

+6

++ , RAII:

{
    CriticalSectionLock lock ( mutex_ );

    Do stuff...
}

, , .

, , ; , , , .

, . , .

- , - , - , . , , , , , . , IO , , , , .

+2

Source: https://habr.com/ru/post/1780101/


All Articles