问题描述
嗨!
我想为WriteDataToPort创建一个单独的线程。如何创建cstring并将其作为参数传递给它。
下面是我的代码片段。
Hi!
I would like to create a separate thread for WriteDataToPort. How to create and pass cstring as parameter to it.
Below is my code snippet.
CString ss=_T("");
while(!feof(fpRead))
{
size_t count = fread(file_buffer, sizeof(char), l_size, fpRead);
for(int i=0; i< count; i++)
{
ss = file_buffer[i];
m_CommPort->WriteDataToPort(ss.GetBuffer(ss.GetLength()));
}
}
void CCommPort::WriteDataToPort(TCHAR* f_WriteData)
{
WaitForSingleObject(m_hWriteCompleteEvent,INFINITE);
ResetEvent(m_hWriteCompleteEvent);
m_bKeyboardWrite =TRUE;
memset(m_szWriteBuff, 0, sizeof(m_szWriteBuff));
tcscpy(m_szWriteBuff, f_WriteData);
SetEvent(m_hWriteEvent);
}
i have tried in this way, but getting exception. Please do the needful.
hThread = CreateThread(NULL,0,WriteDataToPortThread,LPVOID)ss.GetBuffer(ss.GetLength()),0,NULL);
DWORD __stdcall CMainFrame::WriteDataToPortThread(LPVOID lpParam)
{
CString* ss = (CString*)lpParam;
((CMainFrame*)AfxGetMainWnd())->m_CommPort->WriteDataToPort(ss->GetBuffer(ss->GetLength()));
return 0;
}
非常感谢
Sam。
Thanks much
Sam.
推荐答案
AfxBeginThread(YourThreadFunction, &g_MyString, THREAD_PRIORITY_NORMAL);
3)在您的线程函数内(例如YourThreadFunction),在开头将LPVOID p转换为CString *然后您可以将它用作指向您线程中字符串的指针'循环:
3) inside your thread function (e.g. YourThreadFunction), cast LPVOID p to CString * in the beginning and then you can use it as a pointer to string in your thread''s loop:
INT YourThreadFunction(LPVOID p)
{
CString *pStr = (CString *)p;
while (!gCancel)
{
// your loop
}
return 0;
}
它当然是粗糙的,但你明白了。所有关于同时访问,重新分配等的常见注意事项仍然适用。
我通常会创建一个线程接口类,其中包含传递数据所需的所有内容两个线程之间 - 可能包含字符串等。
It is of course crude as, but you get the idea. All the usual pre-cautions about simultaneous access, reallocation and so on will still apply.
I normally create a thread interface class that contains everything that is needed to pass data between 2 threads - which could contain strings amongst other things.
这篇关于如何在不同的线程中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!