将一个函数传递给不同的线程 [英] passing one function to different threads

查看:62
本文介绍了将一个函数传递给不同的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个应用程序,我必须创建多个线程。所以我想尝试制作一个函数并将其传递给不同的线程。最初我创建了两个线程并声明了一个函数传递给它们。我想要做的就是将不同的整数传递给那些线程并在线程函数中显示它,这是我的代码:

I have to create an application where I''ll have to make multiple threads. SoI thought to try making one function and passing it to different threads. Initially I''ve created two threads and have declared one function to be passed to both of them. All I am trying to do is to pass different integers to those threads and display it in the thread function,here is my code:

DWORD WINAPI Name(LPVOID lpParam)
           {
         int *Ptr=(int*)lpParam;

         for(int j=0;j<2;j++)
              {
              cout<<"Thread"<<endl;
              cout<<*Ptr<<endl;
              }

            return 0;
           }
            int main()
            {


            int a=10,b=15,c=25;
           HANDLE thread1,thread2;
           DWORD threadID,threadID2;
           thread2= CreateThread(NULL,0,Name,LPVOID(a),0,&threadID2);
           thread1= CreateThread(NULL,0,Name,LPVOID(b),0,&threadID);


         for(int i=0;i<5;i++)
          {
           cout<<"Main Thread"<<endl;
          }

          if(thread1==NULL)
            {
           cout<<"Couldn''t Create Thread:("<<endl;
           exit(0);
           }
             if(thread2==NULL)
            {
           cout<<"Couldn''t Create Thread:("<<endl;
           exit(0);
            }
                  return 0;
             }





但是这段代码没有正常运行,即compliles很好,启动正常,但后来给出了调试错误。有人可以告诉我我的错误以及如何纠正它因为能够利用一个功能多线程对我来说真的很有帮助。



but this code is not running properly,i.e compliles fine,starts fine but afterwards gives a debugging error. Could someone let let me know of my mistake and how I could correct it coz being able to utilize one function for multiple threads will be really helpful for me.

推荐答案

你通过转换 int 按值传递线程参数到 LPVOID 。这是正确的方法,因为变量是本地的。



但是在你的线程函数中,你正在访问他们作为指针。只需将 LPVOID 转换为 int
$ b $,您必须以类似的方式执行此操作b
You are passing the thread parameters by value by casting int to LPVOID. That is the correct way because the variables are local.

But in your thread function, you are accessing them as pointers. You must do it there in a similar way by just casting the LPVOID to int:
int iParam = (int)lpParam;
for(int j=0;j<2;j++)
{
    cout<<"Thread"<<endl;
    cout<<iParam<<endl;
}


LPVOID(a) -> &a
LPVOID(b) -> &b



删除未使用的c变量。

之前返回0; in你应该调用的主函数:


Remove the unused c variable.
Before return 0; in your main function you should call:

WaitForSingleObject(thread1, INFINITE);
WaitForSingleObject(thread2, INFINITE);



防止程序在线程完成之前退出。


To prevent your program exiting before the threads finish.


这篇关于将一个函数传递给不同的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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