Can I use iterlocked classes set 2 variables in a multithreaded env
I'm new to programming/C# and have a question.. I have multiple threads
reading from files (1 thread/file) on a multicore/cpu machine. A file can
contain either ticks(bid/ask info,etc) or bars(open,high,low,close,vol). I
have a worker class, which is the target of the thread doWork, which reads
the file. A worker/thread can only read either bars or ticks, not both,
that is 1 file will be all bars, or all ticks, etc.. Each thread reads the
ticks or bars into its own buffer.
I don't use generics or inheritance for performance reasons(I'll probably
implement both and test performance). I use a ringbuffer (only 1
read/1writer thread per buffer so this is safe). I also instead check the
type of worker to determine if I have a tick or bar.
What I want to do is then process a tick or bar in order by time.. So when
a worker adds a bar/tick to its buffer, I want it to get the time and
compare to a global mintime, and if it's less, then set the global mintime
and set the global index variable so the main thread will know which index
to use in its list to get the data in order.
Do I have to lock (I avoid locking using a ringbuffer) or use the
interlocked class somehow in both the main and worker?
Code below is pseudocode so not fully correct, but hopefully you get the
idea. I'm looking for the best way performance wise.
In my current implementation, before I call GetTick or GetBar in Main, I
call NextTime on every simworker in a loop and then sort an array in the
main worker list. I think keeping track in the worker thread itself will
be more efficient, just not sure about synchronization. Maybe having to
synchronize will erase any benefit.
Pseudocode EX:
Main()
{
List<worker> workers = new List<worker>;
workers.Add(new worker(0,TICK));
workers.Add(new worker(1,BAR));
workers.Add(new worker(2,TICK));
workers.Add(new worker(3,BAR)); //etcc, etc.. I do this in a loop.
//also start all workers - RunAsync.. then.
if(workers[index].workerType == TICK)
Tick= workers[index].GetTick();
else
Bar b = workers[index].GetBar();
}
public long mintime;
public int index;
class worker : BackgroundWorker
{
RingBuffer<tick> trb
RingBuffer<bar> brb
int idx;
public type workerType;
worker(int i, type wtype)
{ idx = i; workerType = wtype }
doWork()
{while(reader.NextData) ;} //calls callback..
callback(tick t) { trb.add(t); if(t.time < mintime) { mintime=t.time;
index= idx}//???
callback(bar b){ brb.add(b); if(b.time < mintime) { mintime=b.time;
index =idx}
Tick GetTick() { trb.Read();}
Bar GetBar() {brb.Read();{
}
No comments:
Post a Comment