Python

From Tech
Revision as of 17:12, 8 February 2013 by 77.72.146.250 (talk) (Created page with " <nowiki> import ctypes import os import sys IPC_CREAT=00001000 # man shm_overview # for f in `find /lib/lib* -type f `; do nm -D $f|grep sem_open && echo found in library: $f…")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search
import ctypes
import os
import sys

IPC_CREAT=00001000
#  man shm_overview
#  for f in `find /lib/lib* -type f `; do nm -D $f|grep sem_open && echo found in library: $f; done
locksUsed=0
class Lock:
    def __init__(self):
        #http://www.dailyfreecode.com/code/create-shared-memory-print-id-shared-2183.aspx
        global locksUsed
        self.fname="/tmp/Py-Lock%4i"%locksUsed

        self.libc = ctypes.cdll.LoadLibrary("/lib/libc.so.6")
        self.librt = ctypes.cdll.LoadLibrary("/lib/librt.so.1")

        f=open(self.fname,"w")
        f.write("0")
        f.close()
        self.key=self.libc.ftok(fname, 0x55)
        print "ftok returned:", self.key
        r=self.libc.semget(self.key, 1, IPC_CREAT|0666)
        print "semget returned: ",r
        
        si=self.librt.sem_init(self.mem, 1, 1)
        print "sem_init returned:", si
        locksUsed+=1

    def acquire(self):
        self.librt.sem_wait(self.sm)

    def release(self):
        self.librt.sem_post(self.sm)

#class Lock_POSIX:
#    def __init__(self):
#        global locksUsed
#        self.librt = ctypes.cdll.LoadLibrary("/lib/libpthread.so.0")
#
#        try:
#            self.librt.sem_unlink("/PyLock%4i"%locksUsed)
#        except:
#            pass
#        self.sm=self.librt.sem_open("/PyLock%4i"%locksUsed, os.O_RDWR|os.O_CREAT, 0x1ff, 1)
#        if sm==0:
#            print "sem_open returned:", self.sm
#            sys.exit()
#        #si=self.librt.sem_init(self.sm, 1, 1)
#        print "sem_init returned:", si
#        if self.sm>=0:
#            locksUsed+=1
#
#    def acquire(self):
#        self.librt.sem_wait(self.sm)
#
#    def release(self):
#        self.librt.sem_post(self.sm)

if __name__== "__main__":
    import time
    import random
    from multiprocessing import Process
    l=Lock()
    def fight(i):
        for j in range(10):
            l.acquire()
            for k in range(10):
                print i
                time.sleep(random.random()/30.)
            print
            l.release()
            
    Process(target=fight, args=(1,)).start()
    Process(target=fight, args=(2,)).start()
    Process(target=fight, args=(3,)).start()
    Process(target=fight, args=(4,)).start()