ข้อจำกัด global interpreter lock (GIL) คือ CPython จะทำงานเพียง thread เดียว แม้ว่าจะเขียนโปรแกรมแบบใช้ multi-thread ก็ตาม และ GIL ถูกพัฒนามาพร้อมกับ CPython ตั้งแต่ปี ค.ศ.1992 โดยข้อจำกัด global interpreter lock (GIL) นี้ มีเฉพาะใน CPython และ PyPy
สาเหตุที่ต้องมี GIL เพราะ CPython มีการจัดการหน่วยความจำ thread ที่ไม่ปลอดภัย (อ้างอิง [1])
สำหรับผู้ที่ต้องการสัมผัสประสบการณ์ global interpreter lock (GIL) เข้าไปโหลดโค้ดมารันทดลองได้ที่ https://github.com/centralniak/gil
ผลลัพธ์


พบว่า Jython ที่ไม่มี GIL ทำงานได้เร็วกว่า CPython ที่มี GIL ด้วยเหตุนี้เอง GIL เป็นส่วนหนึ่งที่ทำให้ CPython ทำงานได้ช้า เมื่อต้องการรันแบบ multi-thread
การแก้ไขหรือหลบข้อจำกัด global interpreter lock (GIL) มีดังนี้
- เปลี่ยนจาก threading เป็น multiprocessing (ไม่ใช่การกำจัด global interpreter lock (GIL) แต่เป็นการแยก interpreter ออกมาโดย GIL เป็นอิสระต่อกัน ใช้หน่วยความจำเพิ่มขึ้นกว่าเดิม)
- เปลี่ยนไป pypy-stm (pypy รุ่นไม่มี GIL ) http://doc.pypy.org/en/latest/stm.html
- เปลี่ยนไปใช้ Jython / IronPython เนื่องจากไม่มี GIL
- เขียนโปรแกรมที่ไม่ต้องการ GIL บนภาษา C/C++ แล้วเรียกใช้งานผ่าน Python
- ใช้ Cython (https://cython.readthedocs.io/en/latest/src/userguide/external_C_code.html#releasing-the-gil) หรือ numba (http://numba.pydata.org/numba-doc/dev/user/jit.html#nogil)
การที่ CPython มี GIL เป็นประเด็นโต้เถียงกันในชุมชนนักพัฒนา Python มาเป็นเวลานานจนถึงปัจจุบัน มีทั้งฝ่ายสนับสนุน GIL และฝ่ายที่ต้องการเอา GIL ออกไป แต่ไม่ใช่เรื่องง่ายที่นำ GIL ออกไปจาก CPython (อ่านเพิ่มเติมได้จาก [1] และ [2] ลิงค์ข้างล่าง)
Reports of the GIL's death have been greatly exaggerated.
— Guido van Rossum (@gvanrossum) 23 กรกฎาคม 2558
และเพราะ GIL จึงทำให้กูเกิลสร้าง Grumpy ตัวแปลงโค้ด Python เป็น Go ขึ้นมา เนื่องจากโค้ดจำนวนมากของกูเกิลใช้งาน CPython 2.7 ตัวอย่างเช่น YouTube ซึ่งต้องรองรับการร้องขอนับล้านต่อวินาที (อ่านเพิ่มเติม https://opensource.googleblog.com/2017/01/grumpy-go-running-python.html)
Gilectomy
Gilectomy เป็นโครงการหนึ่งที่นำ GIL ออกไปจาก CPython https://github.com/larryhastings/gilectomy/tree/gilectomy
ที่มา : https://lwn.net/Articles/689548/
แหล่งอ้างอิง
- [1] Python wiki : https://wiki.python.org/moin/GlobalInterpreterLock
- [2] It isn't Easy to Remove the GIL - Artima : http://www.artima.com/weblogs/viewpost.jsp?thread=214235
- Guido is Right to Leave the GIL in Python, Not for Multicore but for Utility Computing : https://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/
- Van Rossum: Python is not too slow : http://www.infoworld.com/article/2619428/python/van-rossum--python-is-not-too-slow.html
- Why Was Python Written with the GIL? : https://softwareengineering.stackexchange.com/a/186909
0 ความคิดเห็น:
แสดงความคิดเห็น
แสดงความคิดเห็นได้ครับ :)