What is Atomic Operations in Python?

Question:

I’m a beginner in Python. Now I read about Threading and I have some questions.

IMO Atomic Operations (AO) = the simplest operation. the simplest operation in dev is a = 1. But I did read the article (http://preshing.com/20130618/atomic-vs-non-atomic-operations/) and I got the impression that it did not the simplest operationAO. The author told us this operation divided into two operations and this operation wasn’t AO. That this operation was AO it had to have another type. But I must say he told about C/C++ and bytecode, I think the same in Python. How I understood this depend on a type and maybe compiler. BUT Python is dynamic types of language. It has no types.

And I decided to ask the community these questions:

  1. What are Atomic Operations in Python?

  2. Which operations are AO in Python?

If the simple operation isn’t simple then I do not understand what is Atomic Operations.

Asked By: Pro

||

Answers:

The Python documentation’s FAQ seems to have a pretty good answer to this question under What kinds of global value mutation are thread-safe?

I hope you understand the difference between a local stack variable, or a variable otherwise private to a particular thread, that won’t have issues with thread safety, and a global or shared variable that will.

Answered By: CryptoFool

Python atomic for shared data types.

https://sharedatomic.top

The module can be used for atomic operations under multiple processs and multiple threads conditions. High performance python! High concurrency, High performance!

atomic api Example with multiprocessing and multiple threads:

You need the following steps to utilize the module:

  1. create function used by child processes, refer to UIntAPIs, IntAPIs, BytearrayAPIs, StringAPIs, SetAPIs, ListAPIs, in each process, you can create multiple threads.

     def process_run(a):
       def subthread_run(a):
         a.array_sub_and_fetch(b'x0F')
    
       threadlist = []
       for t in range(5000):
           threadlist.append(Thread(target=subthread_run, args=(a,)))
    
       for t in range(5000):
           threadlist[t].start()
    
       for t in range(5000):
           threadlist[t].join()
    
  2. create the shared bytearray

    a = atomic_bytearray(b'ab', length=7, paddingdirection='r', paddingbytes=b'012', mode='m')
    
  3. start processes / threads to utilize the shared bytearray

     processlist = []
    
     for p in range(2):
    
       processlist.append(Process(target=process_run, args=(a,)))
    
     for p in range(2):
    
       processlist[p].start()
    
     for p in range(2):
    
       processlist[p].join()
    
     assert a.value == int.to_bytes(27411031864108609, length=8, byteorder='big')
    
Answered By: Xiquan Ren
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.