zoukankan      html  css  js  c++  java
  • MFC 中线程传递CString 是不安全的 转

     MFC 中线程传递CString 是不安全的 
         在MFC中,向线程传递CString变量参数时,很容易犯一个错误,就是使用一个超出生存期的变量,在主函数中定义的CString变量是局部变量,当主函数结束时,这个CString变量就会被析构,而却在另一个线程中继续使用,参数传递就会出现问题。
         解决此问题,可以在主函数中new一个CString,在线程结束时在delete一下释放内存。或者声明一个全局变量,保证CString变量不会超出生存期,这样传递进线程的参数就可以正常使用了。
         下面为示例代码: 
     1 DWORD WINAPI test::ProcessNotifyThread(LPVOID pParam)
     2 {
     3 
     4     CString* sTest = (CString*)pParam;
     5     //AfxMessageBox(*sTest);
     6     delete sTest;
     7     return 0 ;
     8 }
     9 
    10 void test::OnBnClickedButton1()
    11 {
    12     // TODO: Add your control notification handler code here
    13      CString *sTest = new CString;
    14      *sTest = "hello";
    15      LPVOID lpvoid=sTest;
    16 
    17     CWinThread* pThread = AfxBeginThread((AFX_THREADPROC)test::ProcessNotifyThread, lpvoid);
    18 }
         CString类是很好用,但在多线程时最好不要用CString,因为MSDN明确说了,CString类是非线程安全的。
         下面为摘抄的:

         CString只保证类级的线程安全, 
         要做到对象级别的线程安全,需要你自己进行同步, 也就是说, 可以同时有N个线程在读, 但是写的时候,必须保证没有任何线程"正在"读和写 才可以写入.

    1 CString str; 

    3 CCriticalSection cs; 
    4 cs->Lock( ); 
    5 str+="abcdefg";.. 
    6 do anything you want 
    7 cs->Unlock( );


    线程传递char*

     1 DWORD WINAPI test::ProcessNotifyThread(LPVOID pParam)
     2 {
     3 
     4     char *pSectionName = (char *)lpvoid;
     5     CString sSectionName;
     6     sSectionName.Format("%s", pSectionName);     return 0 ;
     7  }
     8  
     9  void test::OnBnClickedButton1()
    10  {
    11      // TODO: Add your control notification handler code here
    12       CString str = _T("aaaa");
    13       const char *pSectionName = (LPCTSTR)str;     
    14       CWinThread* pThread = AfxBeginThread((AFX_THREADPROC)test::ProcessNotifyThread, (LPVOID)pSectionName);
    15  }

     

     

  • 相关阅读:
    第六次实训作业
    事件处理程序
    第四次实训作业
    I/O流
    课程总结
    求和计算器
    常用类的课后作业
    窗口实训1
    课后练习----实现窗口的切换
    第五次实训作业继承
  • 原文地址:https://www.cnblogs.com/love6tao/p/6889399.html
Copyright © 2011-2022 走看看