A process that initializes a Realsense pipeline periodically, freezes after a single cycle, when sharing context. Here is a minimal recreating code:
import pyrealsense2 as rs
from multiprocessing import Process
ctx = rs.context()
class RS:
def __init__(self):
print("init")
pipe = rs.pipeline(ctx)
print(pipe)
class Proc(Process):
def __init__(self):
super(Proc, self).__init__()
def run(self):
for i in range(10):
print(i)
RS()
print("after")
vs = Proc()
vs.start()
If the context isn't shared, the code crashes after 337 cycles:
import pyrealsense2 as rs
from multiprocessing import Process
class RS:
def __init__(self):
print("init")
ctx = rs.context()
pipe = rs.pipeline(ctx)
print(pipe)
class Proc(Process):
def __init__(self):
super(Proc, self).__init__()
def run(self):
for i in range(400):
print(i)
RS()
print("after")
vs = Proc()
vs.start()
When working with a thread instead of a process this doesn't happen.
In the first code snippet (when working with a global ctx
), you initialise ctx
in the main process, then create a new process which accesses that ctx
.
In the second code snippet (ctx
inside __init__
), you initialise a new context in every loop iteration.
You need to combine the two: to initialise the context in the new process but only once. Something like that:
ctx = None
class RS:
def __init__(self):
global ctx
if ctx is None:
ctx = rs.context()
print("init")
pipe = rs.pipeline(ctx)
print(pipe)