Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Semaphore Objects

Give Feedback

In this lesson, you’ll learn what a semaphore is and see an example program that uses semaphores to protect a limited resource. If you download the sample code, you can get your own copy of


Sample Code (.zip)

12.9 KB

To learn more, you can also check out the documentation.

philipwong37 on Dec. 13, 2019

I am using the concurrent.future to run multi-threads within a for loop and i am able to get the result back (pandas dataframes using future.result()); however, the result return was not in order of of the for-loop above I will need to put the dataframes back into a Python dictionary (two-level keys) the same order as the for-loop above. How do I achieve that? using queue and event ..etc? Thanks. the for-loop could be 1 x 3 or 4 x 3 …etc

Lee RP Team on Dec. 17, 2019

Hey philipwong37,

You may want to look at threading.Barrier which can let you set a barrier so the threads return in the order you want.

philipwong37 on Dec. 17, 2019

Thanks. I was able to trace down to lowest level of the dictionary and do

mydict[key1][key2] = [futures.result() for futures in concurrent.futures.as_completed(mydict)]

the mydict stored all result from the for-loop in the multi-thread.

and put back to the correct keys of the dictionary. However, I have another issue. I have noticed and cannot use multi-threads along different part of the process. The memory will not release after doing multi-thread, and technically I have to find the part of the process that is essential to use multi-thread and I can only use it once?

Become a Member to join the conversation.