Click to See Complete Forum and Search --> : help me with mutex in threads


majordomas
January 12th, 2005, 03:51 PM
I have a table with strings (CStringArray) and I want my threads to read data from it but no to dublicate it. First thread read first string ....., fifth thread read fifth string etc.


global variables CStringArray lista,CMutex lock;
in header file:
//start

public:
static UINT WorkerThreadProc (LPVOID param); //controlling function header
typedef struct THREADSTRUCT //structure for passing to the controlling function
{
CThreadDlg* _this;

} THREADSTRUCT;


///end







lista.Add("xxxxxxxxx");
lista.Add("aaaaaaaaaa");
lista.Add("bbbbbbbb");
lista.Add("ccccccccc");
lista.Add("ddddddddd");
lista.Add("eeeeeeeeeee");
lista.Add("fffffffffffff");
lista.Add("zzzzzzzzzzz");


void CThreadDlg::OnOK()
{
THREADSTRUCT *_param = new THREADSTRUCT;
_param->_this = this;
for(int i=0;i<5;i++) //starting 5 threads
{
AfxBeginThread(WorkerThreadProc,_param,THREAD_PRIORITY_NORMAL,0,0,NULL);
}



}



UINT CThreadDlg::WorkerThreadProc( LPVOID param )
{
THREADSTRUCT* ts = (THREADSTRUCT*)param;
CSingleLock lock(&g_m,&g_C);
lock.Lock();


ts->_this->OnGo();

lock.Unlock();

return 1;
}

void CThreadDlg::OnGo()
{
for(int i=0;i<lista.GetSize();i++)
{
MessageBox(lista[i]);
}
}

I don't know how to use cmutex lock() und unlock();

Andreas Masur
January 12th, 2005, 04:23 PM
[ Moved thread ]

MrViggy
January 12th, 2005, 05:16 PM
How many threads are going to be writing to the array? And is it possible for writing to occur when another thread is reading the array?

I'm asking because if you only write to the array once (to initialize it), then you only ever read from the array, then locking should not be necessary. AFAIK, reading from a CStringArray will not change the object in any way.

But, to actually answer your question, you don't need to access the CMutex directly. CSingleLock handles that for you.

However, I do notice that you're calling CWnd::MessageBox from your thread. You don't want to do that. Use the global ::MessageBox function instead. Or, if you want to access other UI elements, check out:

http://www.codeguru.com/forum/showthread.php?t=312454

Viggy

majordomas
January 15th, 2005, 02:21 PM
I want only to ready from CStringArrays . I run 5 threads and each thread reads other string.

Thanks for help.