Visual Studi C ++中的线程 [英] Threads in visual studi c++

查看:90
本文介绍了Visual Studi C ++中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,
我是一个初学者.我正在编写一个程序,该程序将无限循环地显示随机字母,直到用户单击"enter"为止.线程似乎工作正常,但是线程执行后的程序执行混乱了.与之类似,对于该部分之后的后续问题,输入未正确接受.如果线程被删除,则工作正常.我尝试到处寻找,但找不到任何解决方案.非常感谢您的帮助.谢谢.


这是处理线程的代码部分.请让我知道任何错误.另外,如果问题出在内存分配/访问上,您能否详细说明如何解决?顺便说一句,我也尝试使用_beginthread(),但遇到了同样的问题.

Hey,
I''m a beginner in this. I''m writing a program that will keep displaying random letters in an infinite loop till the user hits ''enter''. The thread seems to work fine but the program execution after the execution of the thread gets messed up. As in, for the questions that follow after that part the input is not accepted properly. If the thread is removed it works fine. I tried looking everywhere but couldn''t find any solution. Would really appreciate some help. Thanks.


This is the part of the code that deals with the thread. Please let me know of any mistakes. Also, can you please elaborate on how to fix it if the problem is with the memory allocation/access? By the way, I also tried using _beginthread() but experienced the same problem.

// The function passed in the thread
// c has been declared as a global variable
DWORD WINAPI StopMatrix(LPVOID)
{
 c=''\0'';
 c=getchar();
 while(c!=''\n'')
  c=getchar();
 return 0;
}
 
// Function containing the thread creation.
void RandomMatrixPrint()
{
 HANDLE ThreadVar=0;
 for(int x=0;x<;999;x++)
 {
  for(int i=0;i<10;i++)
  {
   for(int j=0;j<;10;j++)
   cout<<matrix[i][j];
   cout<<"\n";
   if(x<3)
    Sleep(1);
   else
    Sleep(35);
  }
  ThreadVar=CreateThread(NULL,0,StopMatrix,NULL,0,NULL);
  if(c==''\n'')
  break;
 }
 system("cls");
 CloseHandle(ThreadVar);
}

推荐答案

您需要编写一些代码来查看出了什么问题,这很可能是您使用共享内存而不是分配/访问正确用于独立线程.

更新:查看您的代码,您在for循环中有CreateThread(),for循环将在继续运行之前不等待线程完成,因此您可能最终会创建多个线程,并且所有线程都访问同一个全局变量c.这是线程出错了... :)

我建议您仔细阅读CreateThread教程(此处是 [
You need to put some code up to see what''s going wrong, its likely you''re using shared memory and not allocating/accessing correctly for use with independent thread.

Update: Looking at your code, you have CreateThread() within a for loop, the for loop will not wait for the thread to be done before moving on, therefore you may end up with multiple threads being created and all accessing the same global variable c. This is threads gone wrong... :)

I would suggest going through a CreateThread tutorial (here''s one[^]) to learn how to use it properly.


这篇关于Visual Studi C ++中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆