本文为英文翻译,原文地址:Concurrency
Concurrency
SystemC使用仿真过程建模并发操作,并非真实的并发运行。
当有多个仿真过程进行并发仿真,在某一时刻只有一个仿真过程在运行。
当然,仿真时间在所有的仿真过程完成当前任务前不会变化,也就是可以认为:这些仿真过程在相同的仿真时间是并行运行的。这一点和一些其他编程语言不同,例如Go等,可以真正并行操作。
下面看下示例以理解仿真并行:
// Learn with Examples, 2020, MIT license
#include <systemc>
using namespace sc_core;
SC_MODULE(CONCURRENCY) {
SC_CTOR(CONCURRENCY) { // constructor
SC_THREAD(thread1); // register thread1
SC_THREAD(thread2); // register thread2
}
void thread1() {
while(true) { // infinite loop
std::cout << sc_time_stamp() << ": thread1" << std::endl;
wait(2, SC_SEC); // 2秒(仿真时间)后再次触发
}
}
void thread2() {
while(true) {
std::cout << "\t" << sc_time_stamp() << ": thread2" << std::endl;
wait(3, SC_SEC); // 3秒(仿真时间)后再次触发
}
}
};
int sc_main(int, char*[]) {
CONCURRENCY concur("concur"); // define an object
sc_start(10, SC_SEC); // run simulation for 10 seconds
return 0;
}
0 s: thread1 # thread1 is running
0 s: thread2 # thread2 is running
2 s: thread1 # thread1 is running
3 s: thread2 # thread2 is running
4 s: thread1 # thread1 is running
6 s: thread2 # thread2 is running
6 s: thread1 # thread1 is running
8 s: thread1 # thread1 is running
9 s: thread2 # thread2 is running
# simulation ends after 10 simulated seconds