Implementation:CARLA simulator Carla Sensor Stop Destroy
| Knowledge Sources | |
|---|---|
| Domains | Simulation, Perception |
| Last Updated | 2026-02-15 00:00 GMT |
Overview
Concrete tool for stopping sensor data streams and destroying sensor actors to cleanly tear down a data collection rig provided by the CARLA simulator.
Description
Sensor.stop() deregisters the sensor's callback and terminates the client-side data stream. After this call, no further callback invocations will occur for that sensor. Sensor.destroy() sends an RPC request to the CARLA server to remove the sensor actor, releasing all associated server-side resources (GPU render targets, ray-casting state, network streams). The method returns True if the actor was successfully destroyed, or False if it was already destroyed or invalid.
These methods must be called in sequence -- stop() before destroy() -- to prevent dangling callback invocations on a destroyed actor. After all sensors are cleaned up, World.apply_settings() should be called to restore the original world settings (typically re-enabling asynchronous mode).
Usage
These methods are called at the end of a data collection session, inside a finally block to guarantee execution even if the collection loop raises an exception. They are also used when dynamically reconfiguring a sensor suite during a session.
Code Reference
Source Location
- Repository: CARLA
- File:
PythonAPI/carla/src/Sensor.cpp(L22-40),LibCarla/source/carla/client/ServerSideSensor.cpp - Lines: L22-40 (Python bindings), ServerSideSensor.cpp (C++ implementation)
Signature
Sensor.stop() -> None
Sensor.destroy() -> bool
Import
import carla
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| (none) | -- | -- | stop() takes no arguments. It operates on the sensor instance. |
| (none) | -- | -- | destroy() takes no arguments. It operates on the sensor instance. |
Outputs
| Name | Type | Description |
|---|---|---|
| (none) | None | stop() returns None. The callback is deregistered and no further data events will fire. |
| success | bool | destroy() returns True if the server-side actor was successfully removed, False if the actor was already destroyed or invalid. |
Usage Examples
Basic Example
import carla
client = carla.Client('localhost', 2000)
client.set_timeout(10.0)
world = client.get_world()
# Save original settings
original_settings = world.get_settings()
# Enable synchronous mode
settings = world.get_settings()
settings.synchronous_mode = True
settings.fixed_delta_seconds = 0.05
world.apply_settings(settings)
# Spawn a sensor (assume ego_vehicle exists)
ego_vehicle = world.get_actors().filter('vehicle.*')[0]
bp = world.get_blueprint_library().find('sensor.camera.rgb')
bp.set_attribute('image_size_x', '1920')
bp.set_attribute('image_size_y', '1080')
sensor = world.spawn_actor(
bp,
carla.Transform(carla.Location(x=1.5, z=2.4)),
attach_to=ego_vehicle
)
sensor.listen(lambda img: img.save_to_disk(f'output/{img.frame:06d}.png'))
try:
for _ in range(100):
world.tick()
finally:
# Proper teardown: stop -> destroy -> restore settings
sensor.stop()
sensor.destroy()
world.apply_settings(original_settings)
Full Multi-Sensor Cleanup
import carla
import queue
client = carla.Client('localhost', 2000)
client.set_timeout(10.0)
world = client.get_world()
original_settings = world.get_settings()
settings = world.get_settings()
settings.synchronous_mode = True
settings.fixed_delta_seconds = 0.05
world.apply_settings(settings)
bp_lib = world.get_blueprint_library()
ego_vehicle = world.get_actors().filter('vehicle.*')[0]
# Spawn multiple sensors
sensor_configs = [
('sensor.camera.rgb', carla.Transform(carla.Location(x=1.5, z=2.4))),
('sensor.camera.depth', carla.Transform(carla.Location(x=1.5, z=2.4))),
('sensor.camera.semantic_segmentation', carla.Transform(carla.Location(x=1.5, z=2.4))),
('sensor.lidar.ray_cast', carla.Transform(carla.Location(z=2.5))),
('sensor.other.radar', carla.Transform(carla.Location(x=2.5, z=0.7))),
('sensor.other.gnss', carla.Transform()),
('sensor.other.imu', carla.Transform()),
]
sensors = []
queues = []
for bp_id, transform in sensor_configs:
bp = bp_lib.find(bp_id)
if bp_id == 'sensor.camera.rgb':
bp.set_attribute('image_size_x', '1920')
bp.set_attribute('image_size_y', '1080')
sensor = world.spawn_actor(bp, transform, attach_to=ego_vehicle)
q = queue.Queue()
sensor.listen(q.put)
sensors.append(sensor)
queues.append(q)
try:
# Data collection loop
for frame_num in range(500):
frame_id = world.tick()
# Collect data from all queues
frame_data = []
for q in queues:
try:
data = q.get(timeout=2.0)
frame_data.append(data)
except queue.Empty:
print(f"Missing data at frame {frame_id}")
break
if frame_num % 100 == 0:
print(f"Collected frame {frame_id} ({frame_num + 1}/500)")
finally:
# CLEANUP: Stop all sensors first, then destroy all actors
print("Stopping sensor streams...")
for sensor in sensors:
sensor.stop()
print("Destroying sensor actors...")
for sensor in sensors:
success = sensor.destroy()
if not success:
print(f"Warning: failed to destroy sensor {sensor.id}")
# Restore original world settings (re-enable async mode)
print("Restoring world settings...")
world.apply_settings(original_settings)
print("Cleanup complete.")
Batch Destruction for Large Sensor Suites
import carla
# For large sensor suites, use batch commands for faster teardown
client = carla.Client('localhost', 2000)
client.set_timeout(10.0)
world = client.get_world()
# Assume sensors is a list of spawned sensor actors
sensors = [...] # populated during setup
# Step 1: Stop all callbacks (must be done individually)
for sensor in sensors:
sensor.stop()
# Step 2: Batch destroy all sensor actors in a single RPC call
destroy_commands = [carla.command.DestroyActor(sensor) for sensor in sensors]
responses = client.apply_batch_sync(destroy_commands)
# Check results
for i, response in enumerate(responses):
if response.error:
print(f"Failed to destroy sensor {i}: {response.error}")
# Step 3: Restore world settings
world.apply_settings(original_settings)