| 
									
										
										
										
											2020-05-19 03:03:25 -07:00
										 |  |  | """High-level support for working with threads in asyncio""" | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | import functools | 
					
						
							| 
									
										
										
										
											2020-05-20 22:38:00 -07:00
										 |  |  | import contextvars | 
					
						
							| 
									
										
										
										
											2020-05-19 03:03:25 -07:00
										 |  |  | 
 | 
					
						
							|  |  |  | from . import events | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | __all__ = "to_thread", | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  | async def to_thread(func, /, *args, **kwargs): | 
					
						
							|  |  |  |     """Asynchronously run function *func* in a separate thread.
 | 
					
						
							|  |  |  | 
 | 
					
						
							|  |  |  |     Any *args and **kwargs supplied for this function are directly passed | 
					
						
							| 
									
										
										
										
											2020-05-20 22:38:00 -07:00
										 |  |  |     to *func*. Also, the current :class:`contextvars.Context` is propogated, | 
					
						
							|  |  |  |     allowing context variables from the main thread to be accessed in the | 
					
						
							|  |  |  |     separate thread. | 
					
						
							| 
									
										
										
										
											2020-05-19 03:03:25 -07:00
										 |  |  | 
 | 
					
						
							|  |  |  |     Return an asyncio.Future which represents the eventual result of *func*. | 
					
						
							|  |  |  |     """
 | 
					
						
							|  |  |  |     loop = events.get_running_loop() | 
					
						
							| 
									
										
										
										
											2020-05-20 22:38:00 -07:00
										 |  |  |     ctx = contextvars.copy_context() | 
					
						
							|  |  |  |     func_call = functools.partial(ctx.run, func, *args, **kwargs) | 
					
						
							| 
									
										
										
										
											2020-05-19 03:03:25 -07:00
										 |  |  |     return await loop.run_in_executor(None, func_call) |