clistctrl threadsafe access
I have clist control in my CListView based class. I also defined a function AddMsg to add item to the clist control. This function will be called from many places (threads) in the problem. I wan to have a threadsafe access to the control. I tried to use CCriticalSection for it, but the program will lock up, I think some deadlock is happening. How can I solve it.
CCriticalSection m_CriticalSection;
void CMyView::AddMsg(CString &msg)
{
m_CriticalSection.Lock();
do list control access...
m_CriticalSection.Unlock();
}
Re: clistctrl threadsafe access
how are you accessing this function from the thread(s)? it is not advisible to directly access MFC objects from a thread, you should rather PostMessage() from the thread. In the message handler do whatever you have to. This site has a very good FAQ section on threads, which I recommend checking out.
Re: clistctrl threadsafe access
Re: clistctrl threadsafe access
Thanks for the reply, but if I use PostMessage(), since I will pass the local CString pointer, the pointer will not be valid by the time the message is being pocessed. What should I do?
Re: clistctrl threadsafe access
Quote:
Originally Posted by mwong7025
Thanks for the reply, but if I use PostMessage(), since I will pass the local CString pointer, the pointer will not be valid by the time the message is being pocessed. What should I do?
you can try sommething like this:
Code:
in the thread:
CString strToSend = new CString("From thread");
::PostMessage(m_handleToYourClass, WM_YOUR_CUSTOM_MESSAGE, 0, reinterpret_cast<LPARAM>strToSend);
in the message handler:
CYourClass::OnMessage(WPARAM wParam, LPARAM lParam)
{
std::auto_ptr <CString> strFromThread(reinterpret_cast <CString *>(lParam));
// do something with strFromThread
// additionally there is no need to delete [] anything
}
Re: clistctrl threadsafe access
I'm not so familiar with auto-pointer, but shouldn't this line
Code:
::PostMessage(m_handleToYourClass, WM_YOUR_CUSTOM_MESSAGE, 0,
reinterpret_cast<LPARAM>strToSend);
be
Code:
::PostMessage(m_handleToYourClass, WM_YOUR_CUSTOM_MESSAGE, 0,
reinterpret_cast<LPARAM>&strToSend);
Mike
Re: clistctrl threadsafe access
You cannot use the CListCtrl class from multiple threads because MFC uses thread-local storage to map window handles to MFC objects.
Try to use the window handle of the list control instead of the CListCtrl class. You may use the ListView_* macros defined in commctrl.h that makes most of the work almost painless.
Ah, and by the way: Consider using a CSingleLock with your critical section to wrap syncronization and support exception safety, e.g. like this:
Code:
{
// Lock critical section.
CSingleLock sl(&m_CriticalSection, TRUE);
// Insert new item into list control.
LVITEM lvItem;
memset(&lvItem,0,sizeof(LVITEM));
lvItem.iItem = 0x0fffffff;
const int ciItem(ListView_InsertItem(m_hListCtrl, &lvItem));
}