Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading in c++

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)?

like image 420
gemexas Avatar asked Nov 29 '22 10:11

gemexas


1 Answers

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!

like image 107
Nawaz Avatar answered Dec 05 '22 10:12

Nawaz