How to reduce context switching in concurrent programming

Ways to reduce context switching are lock-free concurrent programming, CAS algorithms, using minimal threads, and using coroutines.
1. Lock-free concurrent programming. When multiple threads compete for locks, context switching will be caused. Therefore, when processing data with multiple threads,
some to avoid the use of locks. For example, the ID of the data is divided into segments according to the Hash algorithm, and different threads process different segments of data.
2. CAS algorithm. Java's Atomic package uses the CAS algorithm to update data without locking.
3. Use minimal threads. Avoid creating unnecessary threads. For example, there are few tasks, but many threads are created to process them,
which will cause a large number of threads to be in a waiting state.
4. Coroutine: realize multi-task scheduling in a single thread, and maintain switching between multiple tasks in a single thread.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325258918&siteId=291194637