ossrs/srs

Threading: Mechanisms for multi-threaded communication, which can refer to Go's chan or Node.js's postMessage.

winlinvip opened this issue · 0 comments

Multi-threaded communication is a series of mechanisms:

  1. First is the efficient communication queue.
  2. Then there is the mechanism for communication between threads.

Mutex vs CAS Int

We only consider the comparison between locks and CAS, that is, the case of int increment.

  • trunk/research/lockless/mutex-int.cpp: Use Mutex, int increment.
  • trunk/research/lockless/lockless-int.cpp: Use CAS, int increment.

First, look at single-threaded, so that waiting and conflict can be eliminated, data is as follows:

Number of threads Synchronization Number of loops Actual number of loops Time consumed
Single thread None 300M 300M 646ms
Single thread Mutex 300M 300M 5373ms
Single thread CAS 300M 300M 1911ms

Then, it's double-threaded, at this time Mutex or CAS must be used, no synchronization will cause data abnormalities and can only be used as a reference, data is as follows:

Number of threads Synchronization Number of loops Actual number of loops Time consumed
2 threads None 60M 65M 468ms
2 threads Mutex 60M 120M 5009ms
2 threads CAS 60M 120M 3295ms

Note: The actual number of loops should be 120M, because there are 2 threads, each with 60M.

Next, test 3 threads, data is as follows:

Number of threads Synchronization Number of loops Actual number of loops Time consumed
3 threads None 50M 60M 677ms
3 threads Mutex 50M 150M 7909ms
3 threads CAS 50M 150M 4317ms

Mutex vs CAS Queue

Consider the circular queue.

  • trunk/research/lockless/mutex-queue.cpp: Use Mutex.
  • trunk/research/lockless/lockless-queue.cpp: Use CAS.

Data is as follows:

Write thread count Read thread count Synchronization Number of loops Time consumed
1 thread 1 thread Mutex 30M 2872ms
1 thread 1 thread CAS 30M 3254ms
2 threads 2 threads Mutex 30M 6233ms
2 threads 2 threads CAS 30M 10387ms
3 threads 3 threads Mutex