I want to run one function with different 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. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With