#### 进程锁
进程锁的位置很重要
```
# -*- coding: utf-8 -*-
from multiprocessing import Process, Lock
import time
lock = Lock()
class ScheduleTest():
@
staticmethod def printx():
while True:
print('hello x')
time.sleep(5)
def run(self):
print('printx is running...')
my_process = Process(target=self.printx)
my_process.start()
def app_run():
my_schedule = ScheduleTest()
for i in range(3):
with lock:
p = Process(target=
my_schedule.run)
p.start()
p.join()
if __name__ == '__main__':
app_run()
```
#### 信号量
信号量其实也是进程锁
```
# -*- coding: utf-8 -*-
from multiprocessing import Process, Semaphore
import time
s = Semaphore(1)
class ScheduleTest():
@
staticmethod def printx():
while True:
print('hello x')
time.sleep(5)
def run(self):
s.acquire()
print('printx is running...')
my_process = Process(target=self.printx)
my_process.start()
my_process.join()
s.release()
def app_run():
my_schedule = ScheduleTest()
process_0 = Process(target=
my_schedule.run)
process_1 = Process(target=
my_schedule.run)
process_2 = Process(target=
my_schedule.run)
process_0.start()
process_1.start()
process_2.start()
if __name__ == '__main__':
app_run()
```
#### 共享变量
共享变量注意需加锁
```
# -*- coding: utf-8 -*-
from multiprocessing import Process, Manager, Lock
import time
manager = Manager()
sum = manager.Value('tmp', 0)
lock = Lock()
class ScheduleTest():
@
staticmethod def printx():
while True:
print('hello x')
time.sleep(5)
def run(self):
with lock:
if not sum.value:
print('printx is running...')
my_process = Process(target=self.printx)
my_process.start()
sum.value += 1
else:
print('printx has ran.')
def app_run():
my_schedule = ScheduleTest()
process_0 = Process(target=
my_schedule.run)
process_1 = Process(target=
my_schedule.run)
process_2 = Process(target=
my_schedule.run)
process_0.start()
process_1.start()
process_2.start()
if __name__ == '__main__':
app_run()
```