Benefits of green threads vs a simple loop -
is there benefit using green threads / lightweight threads on simple loop or sequential code, assuming non blocking operations used in both?
for := 0; < 5; i++ { go dosomethingexpensive() // using golang example } // versus := 0; < 5; i++ { dosomethingexpensive() } as far can think of
- green threads avoid bit of callback hell on async operations
- allow scheduling of m green threads on n kernel threads
but
- add bit of complexity , performance requiring scheduler
- easier cross thread communication when language supports , execution split different cpu's (otherwise sequential code simpler)
no, green threads have no performance benefits at all.
if threads performing non-blocking operations:
multiple threads have no benefits if have 1 physical core (since same core has execute everything, threads makes things slower because of overhead)
up many threads cpu cores have have performance benefit, since multiple cores can execute threads physically parallel (see play! framework)
green threads have no benefits, since running same 1 real thread sub-scheduler, green threads == 1 thread
if threads performing blocking operations, things may different:
- multiple threads makes sense, since 1 thread can blocked, others can go on, blocking slows down 1 thread
- you can avoid callback-hell implementing partially blocking process 1 thread. since you're free block 1 thread while e.g. waiting io, simpler code.
green threads
green threads not real threads design, won't split amongst multiple cpus , not indended work in parallel. can give false understading can avoid synchronization - once upgrade real threads lack of proper synchronization introduce set of issues.
green threads used in java days, when jvm did not support real os threads. variant of green threads, called fibers part of windows operating system, , e.g. ms sql server uses them heavily handle various blocking scenarios without heavy overhead of using real threads.
you can choose not amongst green threads , real threads, may consider continuations (https://www.playframework.com/documentation/1.3.x/asynchronous)
continuations give best of both worlds:
- your code logically looks if linear code, no callback hells
- in reality code executed real threads, if thread getting blocked suspends execution , can switch executing other code. once blocking condition signals, thread can switch , continue code.
this approach quite resource friendly. play! framework uses many threads cpu cores have (4-8) beats high-end java application servers in terms of performance.
Comments
Post a Comment