本文整理汇总了Python中multiprocessing.Array.get_lock方法的典型用法代码示例。如果您正苦于以下问题:Python Array.get_lock方法的具体用法?Python Array.get_lock怎么用?Python Array.get_lock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multiprocessing.Array
的用法示例。
在下文中一共展示了Array.get_lock方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_c
# 需要导入模块: from multiprocessing import Array [as 别名]
# 或者: from multiprocessing.Array import get_lock [as 别名]
c2 = pipecl2.recv() #Blocking
update_c(c1.ravel(),c2.ravel()) #########
print "Running main loop..."
while runflag:
#print uflag1.value
#print uflag2.value
dat1 = uflag1.value
dat2 = uflag2.value
frame = vs.read() #for testing
#datrecv1 = pipeul1.recv() #Blocking
#datrecv2 = pipeul2.recv() #Blocking
#if datrecv1[0] and datrecv2[0]:
if (dat1 == 2) and (dat2 ==2):
#pos3d = calc3d(datrecv2[2].ravel(),datrecv1[2].ravel()) ########
with uarray1.get_lock():
arr1 = np.frombuffer(uarray1.get_obj())
with uarray2.get_lock():
arr2 = np.frombuffer(uarray2.get_obj())
pos3d = calc3d(arr1,arr2)
#print np.asarray(pos3d)
imgpts, jac = cv2.projectPoints(np.float32([np.asarray(pos3d)]).reshape(-1,3), rvecs, tvecs, mtx, dist)
cv2.rectangle(frame,(int(imgpts[0,0,0]) - 2,int(imgpts[0,0,1]) - 2),(int(imgpts[0,0,0]) + 2 ,int(imgpts[0,0,1]) + 2),(255,0,0),1)
#elif not datrecv1[1] or not datrecv2[1]:
elif (dat1 == 0) or (dat2 ==0):
runflag = False
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print "Waiting for both processes to stop..."
示例2: RingBuffer
# 需要导入模块: from multiprocessing import Array [as 别名]
# 或者: from multiprocessing.Array import get_lock [as 别名]
class RingBuffer(object):
"""
A RingBuffer containing complex values.
"""
def __init__(self, size: int):
self.__data = Array("f", 2*size)
self.size = size
self.__current_index = Value("L", 0)
@property
def current_index(self):
return self.__current_index.value
@current_index.setter
def current_index(self, value):
self.__current_index.value = value
@property
def is_empty(self) -> bool:
return self.current_index == 0
@property
def space_left(self):
return self.size - self.current_index
@property
def data(self):
return np.frombuffer(self.__data.get_obj(), dtype=np.complex64)
def __getitem__(self, index):
return self.data[index]
def __repr__(self):
return "RingBuffer " + str(self.data)
def __increase_current_index_by(self, n: int):
self.current_index += n
if self.current_index > self.size:
self.current_index = self.size
def clear(self):
self.current_index = 0
def will_fit(self, number_values: int) -> bool:
return number_values <= self.space_left
def push(self, values: np.ndarray):
"""
Push values to buffer. If buffer can't store all values a ValueError is raised
:param values:
:return:
"""
n = len(values)
with self.__data.get_lock():
data = np.frombuffer(self.__data.get_obj(), dtype=np.complex64)
data[self.current_index:self.current_index+n] = values
self.__increase_current_index_by(n)
def pop(self, number: int) -> np.ndarray:
"""
Pop number of elements. If there are not enough elements, all remaining elements are returned and the
buffer is cleared afterwards. If buffer is empty, an empty numpy array is returned.
"""
if number > self.current_index:
number = self.current_index
with self.__data.get_lock():
self.current_index -= number
result = np.copy(self.data[0:number])
data = np.frombuffer(self.__data.get_obj(), dtype=np.complex64)
data[:] = np.roll(data, -number)
return result
示例3: acquire_parallel
# 需要导入模块: from multiprocessing import Array [as 别名]
# 或者: from multiprocessing.Array import get_lock [as 别名]
def acquire_parallel(self, worker_cls, worker_args, result_shape, plot=False):
"""
:param worker: Function which the subordinate threads execute as their target
:param proc_fun: Function used by the subordinate threads to process their buffers
:param result_shape: Shape of the buffer which is the result of the entire acquisition.
"""
from multiprocessing import Array, Value, Event
from slab.plotting import ScriptPlotter
import time
acquire_buffer_time = self.samples_per_buffer / (self.samples_per_second)
print('Acquire buffer time %.2e' % acquire_buffer_time)
print('Inter-buffer time %.2e' % self.seconds_per_buffer)
print('Duty Cycle', acquire_buffer_time / self.seconds_per_buffer)
try:
# I don't know why this needs to happen again?
channel = 0
if self.ch1_enabled:
channel |= 1
if self.ch2_enabled:
channel |= 2
pretriggers = C.c_long(0)
flags = U32(513)
ret = self.Az.AlazarBeforeAsyncRead(self.handle,U32(channel),pretriggers,
U32(self.config.samplesPerRecord),
U32(self.config.recordsPerBuffer),
U32(self.config.recordsPerAcquisition),
flags)
# Initialize buffers
buffers = [Array(U8, self.bytes_per_buffer) for _ in range(self.buffer_count)]
for b in buffers:
ret = self.Az.AlazarPostAsyncBuffer(self.handle, b.get_obj(), U32(self.bytes_per_buffer))
self.assert_az(ret, 0, 'Initial Post Buffer')
res_buffer = Array(C.c_longdouble, result_shape)
# Initialize threads
bufs_merged = Value(U32, 1)
buf_ready_events = [Event() for _ in range(self.buffer_count)]
buf_post_events = [Event() for _ in range(self.buffer_count)]
workers = [worker_cls(*(worker_args + (self.config, b, bre, bpe, res_buffer, bufs_merged)))
for b, bre, bpe in zip(buffers, buf_ready_events, buf_post_events)]
for w in workers:
w.start()
time.sleep(1)
import atexit
atexit.register(lambda: [w.terminate() for w in workers])
# Initialize things used during capture
if plot:
plotter = ScriptPlotter()
plotter.init_plot('Data', rank=1, accum=False)
buffers_acquired, buffers_completed, plot_count = 0, 0, 0
start_time = time.time()
# Begin capture
ret = self.Az.AlazarStartCapture(self.handle)
self.assert_az(ret, 0, "Start Capture")
unready_count = 0
while buffers_completed < self.buffers_per_acquisition:
# Post all completed buffers
while buf_post_events[buffers_completed % self.buffer_count].is_set():
buf_post_events[buffers_completed % self.buffer_count].clear()
buf = buffers[buffers_completed % self.buffer_count]
with buf.get_lock():
ret = self.Az.AlazarPostAsyncBuffer(self.handle, buf.get_obj(), U32(self.bytes_per_buffer))
self.assert_az(ret, buffers_acquired, 'Post Buffer')
buffers_completed += 1
# Current buffer rotates in a ring
buf_idx = buffers_acquired % self.buffer_count
buf = buffers[buf_idx]
# Pull data to buffer
with buf.get_lock():
ret = self.Az.AlazarWaitAsyncBufferComplete(self.handle, buf.get_obj(), U32(self.timeout))
if ret == 573:
unready_count += 1
continue # BufferNotReady, go back and try to post some buffers.
else:
self.assert_az(ret, buffers_acquired, 'Wait Buffer Complete')
buffers_acquired += 1
# Tell worker thread to begin processing
buf_ready_events[buf_idx].set()
# If a second has elapsed, replot the avg_buffer
if (time.time() - start_time) / self.seconds_per_plot > plot_count:
if plot:
with res_buffer.get_lock():
plotter.msg(buffers_acquired, buffers_completed, bufs_merged.value)
plotter.plot(np.frombuffer(res_buffer.get_obj()), 'Data')
plot_count += 1
#.........这里部分代码省略.........
示例4: RingBuffer
# 需要导入模块: from multiprocessing import Array [as 别名]
# 或者: from multiprocessing.Array import get_lock [as 别名]
class RingBuffer(object):
"""
A RingBuffer containing complex values.
"""
def __init__(self, size: int):
self.__data = Array("f", 2*size)
self.size = size
self.__left_index = Value("L", 0)
self.__right_index = Value("L", 0)
self.__length = Value("L", 0)
def __len__(self):
return self.__length.value
@property
def left_index(self):
return self.__left_index.value
@left_index.setter
def left_index(self, value):
self.__left_index.value = value % self.size
@property
def right_index(self):
return self.__right_index.value
@right_index.setter
def right_index(self, value):
self.__right_index.value = value % self.size
@property
def is_empty(self) -> bool:
return len(self) == 0
@property
def space_left(self):
return self.size - len(self)
@property
def data(self):
return np.frombuffer(self.__data.get_obj(), dtype=np.complex64)
@property
def view_data(self):
"""
Get a representation of the ring buffer for plotting. This is expensive, so it should only be used in frontend
:return:
"""
left, right = self.left_index, self.left_index + len(self)
if left > right:
left, right = right, left
data = np.frombuffer(self.__data.get_obj(), dtype=np.complex64)
return np.concatenate((data[left:right], data[right:], data[:left]))
def clear(self):
self.left_index = 0
self.right_index = 0
def will_fit(self, number_values: int) -> bool:
return number_values <= self.space_left
def push(self, values: np.ndarray):
"""
Push values to buffer. If buffer can't store all values a ValueError is raised
"""
n = len(values)
if len(self) + n > self.size:
raise ValueError("Too much data to push to RingBuffer")
slide_1 = np.s_[self.right_index:min(self.right_index + n, self.size)]
slide_2 = np.s_[:max(self.right_index + n - self.size, 0)]
with self.__data.get_lock():
data = np.frombuffer(self.__data.get_obj(), dtype=np.complex64)
data[slide_1] = values[:slide_1.stop - slide_1.start]
data[slide_2] = values[slide_1.stop - slide_1.start:]
self.right_index += n
self.__length.value += n
def pop(self, number: int, ensure_even_length=False):
"""
Pop number of elements. If there are not enough elements, all remaining elements are returned and the
buffer is cleared afterwards. If buffer is empty, an empty numpy array is returned.
If number is -1 (or any other value below zero) than complete buffer is returned
"""
if ensure_even_length:
number -= number % 2
if len(self) == 0 or number == 0:
return np.array([], dtype=np.complex64)
if number < 0:
# take everything
number = len(self)
else:
number = min(number, len(self))
with self.__data.get_lock():
#.........这里部分代码省略.........
示例5: Screen
# 需要导入模块: from multiprocessing import Array [as 别名]
# 或者: from multiprocessing.Array import get_lock [as 别名]
class Screen(Device):
def __init__(self, nomenclature="", width=0., height=0., screen_width=0., screen_height=0.):
Device.__init__(self, nomenclature, width, height)
self.screen_width = screen_width
self.screen_height = screen_height
self.count = Array('i', 10000)
def __repr__(self):
r = str(self) + "("
r += "width=" + str(self.width) + "m, "
r += "height=" + str(self.height) + "m, "
r += "length=" + str(self.length) + "m, "
r += "screen_width=" + str(self.screen_width) + "m, "
r += "screen_height=" + str(self.screen_height) + "m )"
return r
def transport(self, particle):
if not self.is_particle_lost(particle):
self.collect(particle)
if self.next:
return self.next.transport(particle)
else:
return particle
else:
return None
def collect(self, particle):
half_screen_width = 0.5 * self.screen_width
half_screen_height = 0.5 * self.screen_height
cell_width = 0.01 * self.screen_width
cell_height = 0.01 * self.screen_height
if half_screen_width > particle.x > -half_screen_width and half_screen_height > particle.y > -half_screen_height:
x = int((particle.x + half_screen_width) / cell_width)
y = int((particle.y + half_screen_height) / cell_height)
with self.count.get_lock():
self.count[100 * x + y] += 1
def num_of_particles(self):
c = 0
for i in self.count:
c += i
return c
def reset(self):
self.count = Array('i', 10000)
if self.next:
self.next.reset()
def show(self):
x = []
y = []
z = []
for i in range(100):
for j in range(100):
x.append(float(i))
y.append(float(j))
z.append(float(self.count[100 * i + j]))
plt.hist2d(x, y, bins=100, weights=z)
plt.colorbar()
plt.show()