在信号发生器的控制脚本中实现多线程可以显著提升效率,尤其是在需要同时处理多个任务(如参数配置、数据采集、实时监控和用户交互)时。以下是实现多线程的详细方法及示例代码,涵盖Python(常用库如
threading
、
concurrent.futures
)和C++(如
std::thread
)的实现。
threading模块
python
import
threading
import
time
import
random
from
your_signal_generator_lib
import
SignalGenerator# 假设的信号发生器库
def
configure_channel(sg, channel, freq, amp):
"""线程任务:配置信号发生器通道"""
print(f"Configuring Channel
{channel}: Freq={freq}Hz, Amp={amp}dBm")
sg.set_frequency(channel, freq)
sg.set_amplitude(channel, amp)
time.sleep(0.1)# 模拟设备延迟
def
monitor_status(sg):
"""线程任务:监控设备状态"""
while
True:
status = sg.get_status()
print(f"Status:
{status}")
time.sleep(1)
if
__name__ ==
"__main__":
sg = SignalGenerator("192.168.1.100")# 初始化设备
# 创建线程
threads = []
for
ch
in
range(1,
3):# 假设有2个通道
freq = random.randint(1e6,
10e6)# 随机频率
amp = random.uniform(-20,
10)# 随机幅度
t = threading.Thread(target=configure_channel, args=(sg, ch, freq, amp))
threads.append(t)
t.start()
# 启动监控线程(设为守护线程,主线程退出时自动结束)
monitor_thread = threading.Thread(target=monitor_status, args=(sg,), daemon=True)
monitor_thread.start()
# 等待所有配置线程完成
for
t
in
threads:
t.join()
print("All channels configured.")
concurrent.futures(更高级的线程池)
python
from
concurrent.futures
import
ThreadPoolExecutor
def
configure_channel_wrapper(args):
"""适配线程池的参数传递"""
sg, channel, freq, amp = args
configure_channel(sg, channel, freq, amp)
if
__name__ ==
"__main__":
sg = SignalGenerator("192.168.1.100")
tasks = [
(sg,
1,
1e6, -10),
(sg,
2,
5e6,
0),
]
with
ThreadPoolExecutor(max_workers=2)
as
executor:
executor.map(configure_channel_wrapper, tasks)
print("Configuration completed.")
SignalGenerator
)不是线程安全的,需加锁:
python
lock = threading.Lock()
def
safe_configure(sg, channel, freq, amp):
with
lock:
sg.set_frequency(channel, freq)
sg.set_amplitude(channel, amp)
daemon=True
,避免主线程退出时阻塞。
std::thread)
cpp
#include
#include
#include
#include
#include
"signal_generator.h"// 假设的信号发生器头文件
std::mutex sg_mutex;// 全局互斥锁
void
configureChannel
(SignalGenerator& sg,
int
channel,
double
freq,
double
amp)
{
std::lock_guard
lock
(sg_mutex)
;// 自动加锁/解锁
sg.setFrequency(channel, freq);
sg.setAmplitude(channel, amp);
std::cout <<
"Channel "
<" configured.n" ;
}
void
monitorStatus
(SignalGenerator& sg)
{
while
(true) {
std::lock_guard
lock
(sg_mutex)
;
std::string status = sg.getStatus();
std::cout <<
"Status: "
<"n" ;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int
main
()
{
SignalGenerator
sg
("192.168.1.100")
;
std::vector threads;
// 启动配置线程
threads.emplace_back(configureChannel, std::ref(sg),
1,
1e6,
-10);
threads.emplace_back(configureChannel, std::ref(sg),
2,
5e6,
0);
// 启动监控线程(分离,不阻塞主线程)
std::thread
monitor_thread
(monitorStatus, std::ref(sg))
;
monitor_thread.detach();
// 等待配置线程完成
for
(auto& t : threads) {
t.join();
}
std::cout <<
"All channels configured.n";
return
0;
}
std::mutex
保护共享资源(如设备对象)。
detach()
避免主线程等待。
std::ref
传递引用(避免拷贝)。
队列(Queue)解耦:
queue.Queue
或C++的
std::queue
+互斥锁)传递任务,避免直接操作设备。
python
import
queue
task_queue = queue.Queue()
def
worker(sg):
while
True:
channel, freq, amp = task_queue.get()
configure_channel(sg, channel, freq, amp)
task_queue.task_done()
# 启动工作线程
threading.Thread(target=worker, args=(sg,), daemon=True).start()
# 主线程添加任务
task_queue.put((1,
1e6, -10))
事件驱动:
threading.Event
实现线程间同步(如等待某个条件满足)。
ThreadPoolExecutor(max_workers=4)
)。
threading
或
concurrent.futures
。
通过多线程,信号发生器控制脚本可以实现高效并行操作,例如在配置通道参数的同时实时监控设备状态,显著提升自动化测试或复杂系统的响应速度。