In a game I'm developing, the GUI thread is catching user actions, and the simulation thread is responsible of handling and responding to them.
To minimize complexity and delay, I predefined all possible action types the user may trigger, and created an array of "opcodes". The GUI thread sets "happened" to the relevant array[opcode]
in real time, and the simulation thread, in the proper position in code, samples array[opcode]
and acts on array[opcode].data
if array[opcode].happened == true
.
The problem is that each opcode has a different set (size, types) of arguments. Currently I'm only allowing string arguments, and parses them in the simulation thread – not very efficient. Another solution I can think of is polymorphic opcode class and dynamically casting it in the simulation thread – ugly.
I named this the "mailbox pattern", but I'm sure someone more clever has solved (and named) it already. A pointer to a more elegant solution would be great.
Best Answer
Instead of using an array, you could use a
vector<EventClass>
(whereEventClass
is whatever type your current array is). Then you could just iterate through the vector and process each event until it's empty, assuming the GUI thread won't be adding events while the simulation thread is processing them (this could be achieved with mutexes of some kind)... You'd then only have to process active events, since the vector would only contain events that have happened. It could work like so:If necessary, you could use a vector of pointers to EventClass objects (but then of course you must destroy them as well):