Tuesday, May 8, 2012

Multiple threads reading from single List, one thread at the time using Lock.. how?

I currently have the following class:



    public List<DB_ROW> DB = new List<DB_ROW>();

class MY_CLASS
{

// contructor executes two READER_THREAD's
public void MY_CLASS()
{
Thread reader_thread_1 = new Thread(READER_THREAD);
Thread reader_thread_2 = new Thread(READER_THREAD);

reader_thread_1.Start();
reader_thread_2.Start();
}

// reader thread fetches a single field from the 'global' database
public void READER_THREAD()
{
List<DB_ROW> ORDERED_DB = GLOBAL.DB.OrderByDescending();
string ID = ORDERED_DB[0].ID;
GLOBAL.DB[original_index].LAST_USED = NOW(); // update LAST_USED time
}
}


*The problem is.. * that both threads execute at the same time, therefor they fetch the same 'ID'. I looked into Lock's and modified my class like this:



   public List<DB_ROW> DB = new List<DB_ROW>();

class MY_CLASS
{

// contructor executes two READER_THREAD's
public void MY_CLASS()
{
Thread reader_thread_1 = new Thread(READER_THREAD);
Thread reader_thread_2 = new Thread(READER_THREAD);

reader_thread_1.Start();
reader_thread_2.Start();
}

static readonly object _locker = (object)GLOBAL.DB;

// reader thread fetches a single field from the 'global' database
public void READER_THREAD()
{
lock(_locker){
List<DB_ROW> ORDERED_DB = GLOBAL.DB.OrderByDescending();
string ID = ORDERED_DB[0].ID;
GLOBAL.DB[original_index].LAST_USED = NOW(); // update LAST_USED time
}
}
}


But it doesn't change anything.. The DB List is outside the class, how can I 'lock' it, so only one READER_THREAD reads and updates it at a time?



Also, I have different threads outside this class updating DB as well, will the lock block them from updating the DB too while READER_THREAD is running or will the lock only apply to READER_THREAD (that's what I need)? Thanks!



RESULT I GET NOW:



  READER_THREAD_1: Fetches ID: 1
READER_THREAD_2: Fetches ID: 1


RESULT I WANT:



  READER_THREAD_1: Fetches ID: 1
READER_THREAD_2: Fetches ID: 2




No comments:

Post a Comment