
    RhH                        d Z ddgZddlmZ ddlZddlZddlZddlZddlZddl	Z	ej                  dk(  rddlZdZnddlZdZd	d
lmZ ej                   ej"                  z  ZdZerdZndZd Z G d d      ZdZ G d d      Zy)zProvides shared memory for direct access across processes.

The API of this package is currently provisional. Refer to the
documentation for details.
SharedMemoryShareableList    )partialNntFT   )resource_tracker   z/psm_wnsm_c                      t         t        t              z
  dz  } | dk\  sJ d       t        t        j                  |       z   }t        |      t         k  sJ |S )z6Create a random filename for the shared memory object.   z_SHM_NAME_PREFIX too long)_SHM_SAFE_NAME_LENGTHlen_SHM_NAME_PREFIXsecrets	token_hex)nbytesnames     4/usr/lib/python3.12/multiprocessing/shared_memory.py_make_filenamer   (   sX     $c*:&;;AFQ;333;g//77Dt9----K    c                       e Zd ZdZdZdZdZdZej                  Z
dZerdndZddZd Zd	 Zd
 Zed        Zed        Zed        Zd Zd Zy)r   a  Creates a new shared memory block or attaches to an existing
    shared memory block.

    Every shared memory block is assigned a unique name.  This enables
    one process to create a shared memory block with a particular name
    so that a different process can attach to that same shared memory
    block using that same name.

    As a resource for sharing data across processes, shared memory blocks
    may outlive the original process that created them.  When one process
    no longer needs access to a shared memory block that might still be
    needed by other processes, the close() method should be called.
    When a shared memory block is no longer needed by any process, the
    unlink() method should be called to ensure proper cleanup.Ni  TFc                    |dk\  st        d      |r,t        t        j                  z  | _        |dk(  rt        d      |(| j                  t        j
                  z  st        d      t        r)|E	 t               }	 t        j                  || j                  | j                        | _        || _        nK| j                  rd|z   n|}t        j                  || j                  | j                        | _        || _        	 |r"|r t        j                  | j                  |       t        j                   | j                        }|j"                  }t%        j$                  | j                  |      | _        t-        j.                  | j                  d       n|r"	 |
t               n|}t1        j2                  t0        j4                  t0        j6                  t0        j8                  |dz	  d	z  |d	z  |      }	 t1        j:                         }|t0        j<                  k(  rd|Kt        t>        j@                  t        jB                  t>        j@                        |t0        j<                        	 t1        jD                  |       t%        j$                  d
||      | _        t1        jD                  |       || _        n|| _        t1        jF                  t0        jH                  d|      }	 t1        jJ                  |t0        jH                  ddd      }t1        jD                  |       	 t1        jL                  |      }t1        jN                  |       t%        j$                  d
||      | _        || _(        tS        | j&                        | _*        y # t        $ r Y +w xY w# t(        $ r | j+                           w xY w# t1        jD                  |       w xY w# t1        jD                  |       w xY w# t1        jN                  |       w xY w)Nr   z!'size' must be a positive integerz4'size' must be a positive number different from zeroz&'name' can only be None if create=True)mode/shared_memory    l    r   )tagnameF)+
ValueError_O_CREXosO_RDWR_flagsO_EXCL
_USE_POSIXr   _posixshmemshm_open_mode_fdFileExistsError_name_prepend_leading_slash	ftruncatefstatst_sizemmap_mmapOSErrorunlinkr   register_winapiCreateFileMappingINVALID_HANDLE_VALUENULLPAGE_READWRITEGetLastErrorERROR_ALREADY_EXISTSerrnoEEXISTstrerrorCloseHandleOpenFileMappingFILE_MAP_READMapViewOfFileVirtualQuerySizeUnmapViewOfFile_size
memoryview_buf)	selfr   createsizestats	temp_nameh_maplast_error_codep_bufs	            r   __init__zSharedMemory.__init__K   sO   qy@AA!BII-DKqy !WXX<bii 7EFF |)+D!#.#7#7  KK!%$ "&DJ%)%@%@sTzd&//KK
 "
dLL40*}}!YYtxx6

 %%djj/B 48L 0dI $5544..z1z)!E3*1*>*>*@*g.J.JJ#/&5$)LL$&KK$=$($+$@$@	'" !" !)  ++E2 &*YYr4%K
++E2!*DJ "
  //))
	/#11--E ''.3"33E:D++E2!YYr4>

tzz*	k + ! !$  J  ++E2, ''. ++E2sJ   >1N A4N! 9A4N? N? +'O (O3 	NN!N<?OO03P
c                 D    	 | j                          y # t        $ r Y y w xY wN)closer2   rH   s    r   __del__zSharedMemory.__del__   s"    	JJL 		s    	c                 L    | j                   | j                  d| j                  ffS )NF)	__class__r   rJ   rT   s    r   
__reduce__zSharedMemory.__reduce__   s)    NN				
 	
r   c                 h    | j                   j                   d| j                  d| j                   dS )N(z, size=))rW   __name__r   rJ   rT   s    r   __repr__zSharedMemory.__repr__   s.    ..))*!DII=		{!LLr   c                     | j                   S )z4A memoryview of contents of the shared memory block.)rG   rT   s    r   bufzSharedMemory.buf   s     yyr   c                     | j                   }t        r6| j                  r*| j                   j                  d      r| j                   dd }|S )z4Unique name that identifies the shared memory block.r   r   N)r+   r%   r,   
startswith)rH   reported_names     r   r   zSharedMemory.name   s?     

$55zz$$S) $

12r   c                     | j                   S )zSize in bytes.)rE   rT   s    r   rJ   zSharedMemory.size   s     zzr   c                 2   | j                   !| j                   j                          d| _         | j                  !| j                  j                          d| _        t        r7| j
                  dk\  r't        j                  | j
                         d| _        yyy)zkCloses access to the shared memory from this instance but does
        not destroy the shared memory block.Nr   r   )rG   releaser1   rS   r%   r)   r!   rT   s    r   rS   zSharedMemory.close   sq     99 IIDI::!JJDJ$((a-HHTXXDH (:r   c                     t         rM| j                  r@t        j                  | j                         t	        j
                  | j                  d       yyy)zRequests that the underlying shared memory block be destroyed.

        In order to ensure proper cleanup of resources, unlink should be
        called once (and only once) across all processes which have access
        to the shared memory block.r   N)r%   r+   r&   
shm_unlinkr   
unregisterrT   s    r   r3   zSharedMemory.unlink   s:     $**""4::.''

OD %:r   )NFr   )r\   
__module____qualname____doc__r+   r)   r1   rG   r!   r"   r#   r(   r%   r,   rP   rU   rX   r]   propertyr_   r   rJ   rS   r3    r   r   r   r   2   s    B  E
CEDYYFE%/TUl+\
M      Er   utf8c                   H   e Zd ZdZedededededdj                  diZ
dZd	 d
 d d dZed        Zd"dddZd Zd Zd Zd Zd Zd Zd Zd Zed        Zed        Zed        Zed        Zed        Zed        Zed        Zd  Z d! Z! e"e#jH                        Z%y)#r   a  Pattern for a mutable list-like object shareable via a shared
    memory block.  It differs from the built-in list type in that these
    lists can not change their overall length (i.e. no append, insert,
    etc.)

    Because values are packed into a memoryview as bytes, the struct
    packing format for any storable value must require no more than 8
    characters to describe its format.qdzxxxxxxx?z%dsNzxxxxxx?x   c                     | S rR   rm   values    r   <lambda>zShareableList.<lambda>  s     r   c                 J    | j                  d      j                  t              S N    )rstripdecode	_encodingrt   s    r   rv   zShareableList.<lambda>  s    g.55i@ r   c                 $    | j                  d      S rx   )rz   rt   s    r   rv   zShareableList.<lambda>  s    g. r   c                      y rR   rm   )_values    r   rv   zShareableList.<lambda>  s    r   )r   r   r      c                     t        | t        t        dj                  f      syt        | t              ryt        | t              ryy)zUsed in concert with _back_transforms_mapping to convert values
        into the appropriate Python objects when retrieving them from
        the list as well as when storing them.Nr   r   r   r   )
isinstancestrbytesrW   rt   s    r   _extract_recreation_codez&ShareableList._extract_recreation_code  s9    
 %#udnn!=>s#u%r   r   c                R  	 |||xs d}|D cg c]r  }t        |t        t        f      s| j                  t	        |         nA| j                  t	        |         | j
                  t        |      | j
                  z  dz   z  fz  t }}t        |      | _        t        d |D              | j                  k(  sJ d}dg| _	        |D ]B  }||d   dk7  r| j
                  nt        |d d       z  }| j                  j                  |       D |D cg c]  }| j                  |       }}t        j                  d| j                  z   dj!                  |      z   | j"                  z   | j$                  z         }t'        |d	|
      | _        nt'        |      | _        |,t*        	t        j,                  d| j                  z   | j(                  j.                  d| j                  g| j                    t        j,                  dj!                        | j(                  j.                  | j0                  g	fd|D          t        j,                  | j"                  | j(                  j.                  | j2                  g	fd|D          t        j,                  | j$                  | j(                  j.                  | j4                  g  y t        |       | _        t7        t        j8                  | j                  | j(                  j.                  d            | _	        y c c}w c c}w )Nrm   r   c              3   8   K   | ]  }t        |      d k    yw)rr   N)r   ).0fmts     r   	<genexpr>z)ShareableList.__init__.<locals>.<genexpr>6  s     9s3x1}9s   r   r   srp    T)rI   rJ   c              3   d   K   | ]'  }t        |t              r|j                        n| ) y wrR   )r   r   encoder   v_encs     r   r   z)ShareableList.__init__.<locals>.<genexpr>Z  s'     P!Jq#$6!((4.A=Ps   -0c              3   @   K   | ]  }|j                          y wrR   )r   r   s     r   r   z)ShareableList.__init__.<locals>.<genexpr>`  s     3Q!((4.3   rr   )r   r   r   _types_mappingtype
_alignmentr   	_list_lensum_allocated_offsetsintappendr   structcalcsize_format_size_metainfojoin_format_packing_metainfo_format_back_transform_codesr   shmr|   	pack_intor_   _offset_data_start_offset_packing_formats_offset_back_transform_codeslistunpack_from)
rH   sequencer   item_formatsoffsetr   _recreation_codesrequested_sizer   s
            @r   rP   zShareableList.__init__*  s   <8/~2H % 	 &dS%L9 ##DJ/,,T$Z83t9+G!+KL< H  !]DN999T^^KKKF ()cD# 7SW^$//S"XN''..v67 AI!8<--d3! ! $__d000!"--. 112N $DNKDH#D)DHDd000	
 )) !'' QxP	 --,, 4(3	 1111 $	 !YDN&*""..HHLL'D#}$!s   A7LL$c                 L   |dk\  r|n|| j                   z   }|| j                   k\  s| j                   dk  rt        d      t        j                  d| j                  j
                  | j                  |dz  z         d   }|j                  d      }|j                  t              }|S )z>Gets the packing format for a single value stored in the list.r    Requested position out of range.8srr   ry   )
r   
IndexErrorr   r   r   r_   r   rz   r{   r|   )rH   positionr   r   
fmt_as_strs        r   _get_packing_formatz!ShareableList._get_packing_formats  s    '1}8(T^^2K&DNNQ,>?@@HHLL((8a<7
 	
 hhwZZ	*
r   c                     || j                   k\  s| j                   dk  rt        d      t        j                  d| j                  j
                  | j                  |z         d   }| j                  |   }|S )z9Gets the back transformation function for a single value.r   r   b)r   r   r   r   r   r_   r   _back_transforms_mapping)rH   r   transform_codetransform_functions       r   _get_back_transformz!ShareableList._get_back_transform  sv     &DNNQ,>?@@++HHLL--8
 	
 "::>J!!r   c                    || j                   k\  s| j                   dk  rt        d      t        j                  d| j                  j
                  | j                  |dz  z   |j                  t                     | j                  |      }t        j                  d| j                  j
                  | j                  |z   |       y)zvSets the packing format and back transformation code for a
        single value in the list at the specified position.r   r   r   rr   r   N)r   r   r   r   r   r_   r   r   r|   r   r   )rH   r   r   ru   r   s        r   !_set_packing_format_and_transformz/ShareableList._set_packing_format_and_transform  s     &DNNQ,>?@@HHLL((8a<7i(		
 66u=HHLL--8		
r   c                 F   |dk\  r|n|| j                   z   }	 | j                  | j                  |   z   }t        j                  | j                  |      | j                  j                  |      \  }| j                  |      } ||      }|S # t        $ r t        d      w xY w)Nr   zindex out of range)
r   r   r   r   r   r   r   r_   r   r   )rH   r   r   r   back_transforms        r   __getitem__zShareableList.__getitem__  s    '1}8(T^^2K	3,,t/F/Fx/PPF%%((2DQ 11(;1  	3122	3s   AB B c                    |dk\  r|n|| j                   z   }	 | j                  |   }| j                  |z   }| j                  |      }t        |t        t        f      s| j                  t        |         }|}nw| j                  |dz      |z
  }t        |t              r|j                  t              n|}t        |      |kD  rt        d      |d   dk(  r|}n| j                  t           |fz  }| j                  |||       t        j                   || j"                  j$                  ||       y # t        $ r t	        d      w xY w)Nr   zassignment index out of ranger   z(bytes/str item exceeds available storager   r   )r   r   r   r   r   r   r   r   r   r   r   r|   r   r   r   r   r   r   r_   )	rH   r   ru   item_offsetr   current_format
new_formatencoded_valueallocated_lengths	            r   __setitem__zShareableList.__setitem__  sO   '1}8(T^^2K	>11(;K,,{:F!55h?N %#u.,,T%[9J!M#66x!|D{R !+5# 6 #\\)4<A =!$44 !KLLb!S(+
!005$9 
 	..	

 	TXX\\6=I3  	><==	>s   /D/ /Ec                 \    t        | j                  | j                  j                        dfS )Nr   rm   )r   rW   r   r   rT   s    r   rX   zShareableList.__reduce__  s     t~~DHHMM:B>>r   c                 ^    t        j                  d| j                  j                  d      d   S )Nrp   r   )r   r   r   r_   rT   s    r   __len__zShareableList.__len__  s$    !!#txx||Q7::r   c                 z    | j                   j                   dt        |        d| j                  j                  dS )NrZ   z, name=r[   )rW   r\   r   r   r   rT   s    r   r]   zShareableList.__repr__  s3    ..))*!DJ<wtxx}}>OqQQr   c                 ^     dj                   fdt         j                        D              S )z=The struct packing format used by all currently stored items.r   c              3   @   K   | ]  }j                  |        y wrR   )r   )r   irH   s     r   r   z'ShareableList.format.<locals>.<genexpr>  s!      
,-D$$Q'
r   )r   ranger   rT   s   `r   formatzShareableList.format  s,     ww 
16t~~1F
 
 	
r   c                 &    d| j                   dz   z  S )z>The struct packing format used for the items' storage offsets.rp   r   r   rT   s    r   r   z#ShareableList._format_size_metainfo  s     dnnq())r   c                      d| j                   z  S )z>The struct packing format used for the items' packing formats.r   r   rT   s    r   r   z&ShareableList._format_packing_metainfo  s     dnn$$r   c                      d| j                   z  S )z>The struct packing format used for the items' back transforms.r   r   rT   s    r   r   z*ShareableList._format_back_transform_codes  s     T^^##r   c                 &    | j                   dz   dz  S )Nr   rr   r   rT   s    r   r   z ShareableList._offset_data_start  s     "a''r   c                 :    | j                   | j                  d   z   S )Nr   )r   r   rT   s    r   r   z%ShareableList._offset_packing_formats  s    &&)@)@)DDDr   c                 :    | j                   | j                  dz  z   S )Nrr   )r   r   rT   s    r   r   z*ShareableList._offset_back_transform_codes  s    ++dnnq.@@@r   c                 ,    t        fd| D              S )zCL.count(value) -> integer -- return number of occurrences of value.c              3   (   K   | ]	  }|k(    y wrR   rm   )r   entryru   s     r   r   z&ShareableList.count.<locals>.<genexpr>
  s     4e5E>4s   )r   )rH   ru   s    `r   countzShareableList.count  s     4t444r   c                 V    t        |       D ]  \  }}||k(  s|c S  t        |d      )zpL.index(value) -> integer -- return first index of value.
        Raises ValueError if the value is not present.z not in this container)	enumerater   )rH   ru   r   r   s       r   indexzShareableList.index  s>      ) 	AOHe~	A y(>?@@r   rR   )&r\   ri   rj   rk   r   floatboolr   r   rW   r   r   r   staticmethodr   rP   r   r   r   r   r   rX   r   r]   rl   r   r   r   r   r   r   r   r   r   classmethodtypesGenericAlias__class_getitem__rm   r   r   r   r      sI   *& 	SsjUu
N J@.	   Gd GR "
,"JB?;R 
 
 * * % % $ $ ( (
 E E A A5
A $E$6$67r   )rk   __all__	functoolsr   r0   r!   r<   r   r   r   r   r5   r%   r&   r   r   O_CREATr$   r    r   r   r   r   r|   r   rm   r   r   <module>r      s    O
-   	    77d?JJ 
**ryy
    BE BEJ 	]8 ]8r   