question

Yue Y avatar image
0 Likes"
Yue Y asked Jacob Gillespie edited

Is FlexSim thread safe?

I would like to create a separate thread using c++ that does some jobs along with FlexSim simulation and the jobs may fire some events or change states of the model, is it feasible? Is FlexSim thread safe for this use case?

FlexSim 19.1.0
thread
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

1 Answer

Jacob Gillespie avatar image
0 Likes"
Jacob Gillespie answered Jacob Gillespie edited

FlexSim is not thread safe. FlexSim is single threaded and so you have to implement your own thread security.

Here is an example module I made that shows how you can have a thread working and then handing off the data to FlexSim. Also here is an example model I made which is set up to use the module.

This module works by starting a thread by calling startthreadexample(). The thread can do any task (in this case it saves a dummy message every 1 sec) and then posts a windows message which causes the main thread to call the registered node which was registered by threadexampleregisternode(). The registered node then calls getthreadexampledata() and then prints the retrieved data. The thread can be stopped by calling stopthreadexample().

I made this module by cloning and modifying the Flexsim Modules SDK.

Let me know if you have any questions.


· 4
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Yue Y avatar image Yue Y commented ·

Thank you! How can I use this dll in this model? When I run this model, it says startthreadexample command doesn't exist.

0 Likes 0 ·
Phil BoBo avatar image Phil BoBo ♦♦ Yue Y commented ·

You need to install the module by copying its directory into your FlexSim\modules directory.

Please download the Module SDK and read the included documentation to understand how to work with modules.

0 Likes 0 ·
Yue Y avatar image Yue Y commented ·

Also, if FlexSim itself is not thread safe and we have an another thread that adds events to the event queue at the same time as FlexSim, how to prevent conflict in this case?

0 Likes 0 ·
Phil BoBo avatar image Phil BoBo ♦♦ Yue Y commented ·

That's what Jacob's example shows how to do.

You don't add events to the event queue from the other thread. You store data in your dll from the other thread that you need for the event, and you use a callback into the dll from the FlexSim main thread to read that data and generate the events.

You can use std::thread and std::mutex to write that data on a separate thread and read it from FlexSim's main thread without conflicts.

1 Like 1 ·