Efficient use of multithreading and static vars

I am reading this:

I only have one symbol (EURUSD) so I guess there is no point using the recommended code:

if( Status("stocknum") == 0 )
// do all static variable writing/initialization here

I have one Analysis Window doing all the processing and staticvar writting (staticvarset), for 4 different timeframes. And I have 4 charts running in each one of those 4 different timeframes. The charts are only reading the static vars.

This is total of 5 threads, right?

The AW writes many static vars and I read somewhere that each access to staticvar creates a threadlock. So is there a way to group them, make ONE threadlock, set the static vars and then continue the program?

Likewise is it better to do the same and group the reading of the static vars in each of the 4 charts?

BTW, I need to use dynamic names for the static vars, I have the interval as part of the varname, so I am using the old style with staticvarset/staticvarget. And I cannot use the pragma {interval} inside the big AW script which handles all 4 timeframes.

You do not need any locks in Analysis window as you are just using one symbol. Since charts do only reading, you don't need locks in charts too. In general when there is one writer you don't need locks in the formula. All calls to StaticVarSet/Get are thread safe.

Hello Tomasz

Here ( AmiBroker 6.26.0 BETA released ) you had said:
"During your formula execution the variable keeps local copy. That is done for speed because accessing shared resource involves thread lock."

So I thought that regardless of safeness, if I put 20 staticvarset in a row, I will have 20 thread locks. So I was wondering if I could have just one.

So there is no such issue?

First of all, you don't have 10 locks. You've got one. Regardless of number of StaticVarSet/Get. Lock is an object that protects shared resource. And there is one lock for all static variables. Secondly, if you have one writer and multiple readers it is non-issue, because AmiBroker uses the most efficient form of multi-thread locking, so called read-write locks see also this that are user-space locks (do not require kernel context switch), that actually lock exclusively ONLY for writing, not for reading, so if you have one writer, there is essentially no overhead at all.
Also overhead of thread sync in static variables even in worst cases is negligible (way less than 1%).
Bottom line: do not over-engineer your formulas. I already done all engineering needed for you inside AmiBroker :slight_smile:

Hi Tomasz

At some point you lost me, I did not get how 20 staticvarset statements require just one write lock. Obviously I am missing some theoretical knowledge here. So I will take your word for it.