在c ++中的多线程 [英] Multithreading in c++

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

问题描述

我想在不同的线程上运行一个具有distinctrent参数的函数。

  int threads = 3; 
int par1 [] = {1,2,3};
int par2 [] = {4,5,6};
for(int i = 0; i< threads; i ++){
// new_thread function(par1 [i],par2 [i]);
}

我对线程一无所知。试图做某些winth Windows API(不能使用其他库),但它不工作。我应该如何实现这一点?并且可以开始编程时间的未知数量的线程(动态获取线程)?

解决方案

Windows的一个示例示例

  #include< Windows.h> 

struct thread_data
{
int m_id;
thread_data(int id):m_id(id){}
};
DWORD WINAPI thread_func(LPVOID lpParameter)
{
thread_data * td =(thread_data *)lpParameter;
cout<< thread with id =<< td-> m_id<< endl;
return 0;
}
int main()
{
for(int i = 0; i <10; i ++)
{
CreateThread(NULL, thread_func,new thread_data(i),0,0);
}
}



在此示例中,每个线程都获得不同的数据,即的 thread_data ,作为参数传递给线程函数 thread_func()



阅读这些知道如何在Windows上创建线程:



http://msdn.microsoft.com/en-us/library/ms682516(VS.85).aspx

http://msdn.microsoft.com/en-us/library/ms682453 (v = vs.85).aspx






此外,您可能也喜欢这个建议: / p>

更好的设计:定义一个可重用的类!


I want to run one function with differrent parameters on different threads.

int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}

I know nothing about threads. Tried to do something winth windows API (cant use other libraries), but it doesnt work. How should i implement this? And it is possible to start unknown number of threads of the time of programming (dynamically getting threads)?

解决方案

One sample example for Windows,

#include <Windows.h>

struct thread_data
{
 int m_id;
 thread_data(int id) : m_id(id) {}
};
DWORD WINAPI thread_func(LPVOID lpParameter)
{
 thread_data *td = (thread_data*)lpParameter;
 cout << "thread with id = " << td->m_id << endl;
 return 0;
}
int main()
{
 for (int i=0; i< 10; i++)
 {
  CreateThread(NULL, 0, thread_func, new thread_data(i) , 0, 0);
 }
}

In this example, each thread gets different data, namely of type thread_data, which is passed as argument to the thread function thread_func().

Read these to know how to create thread on windows:

http://msdn.microsoft.com/en-us/library/ms682516(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms682453(v=vs.85).aspx


Also, you may like this suggestion as well:

Better design : define a reusable class!

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

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