I am sort of new to forums, therefore forgive me for mistakes. I am trying to eliminate a for loop within a function and run the function in multiple threads. Is it possible?. The comment inside the code, explains it. Any reasonsble change that results in a good
multi-threading.

#include <iostream>
#include <windows.h>

class A
{
public:
	A()
	{};
	~A()
	{};

	void set_array()
	{
		for (int i = 0; i < 10; i++)
		{
			m_arr[i] = i;
		}
	}

	void get_array(int arr[])
	{
		for (int i = 0; i < 10; i++)
		{
			arr[i] = m_arr[i];
		}		
	}

private:
	int m_arr[10];
};

class B
{
public:
	B()
	{};
	~B()
	{};

	void copy_array(int arr[])
	{
		for (int i = 0; i < 10; i++)
		{
			m_arr[i] = arr[i];
		}
	}

	int get_array(int arr[])
	{
		for (int i = 0; i < 10; i++)
		{
			arr[i] = m_arr[i];
		}		
	}

	int do_something_with_array(void);

private:
	int m_arr[10];
};

//Comment: I like to take the first for loop out and 
//split this function into 6 different threads.
//c loops and gets passed to each thread.
int B::do_something_with_array(void)
{
	int OutputArray[10] = {0};

	for (size_t c = 0; c < 6; c++)
	{
		for (size_t d = 0; d < 10; d++)
		{
			OutputArray[d] = m_arr[d] + (int)c;
		}
	}

	for (size_t i = 0; i < 10; i++)
	{
		std::cout << OutputArray[i] << std::endl;
	}

	return 0;
}

int main(int argc, char* argv[])
{
	int aArr[10] = {0};
	A a;
	a.set_array();
	a.get_array(aArr);

	B b;
	b.copy_array(aArr);

	b.do_something_with_array();

	return 0;
}

Recommended Answers

All 4 Replies

I'm a C++ and general programming newb, I'm also new to these forums.
But, a huge mistake you made was calling your thread "help". Give it a name, so that it is clear what you need when you read the name.
For example in this case you could have called it: does this multithreaded application work?
If you called it that way, I wouldn't have bothered with the thread because I'm new and don't know how to create good working multithreaded applications.

any..?

I'm assuming this is a kind of simplified version of what you're actually trying to do, since this is a very simple example.

If so, then you can multi-thread your code using an external library, there's no in-built multi-threading in C/C++. Popular cross-platform libraries for this are the Boost.Thread library and QThread in the Qt library (there's probably a GTK version as well). In Linux, you can use pthread_create() , as part of POSIX (I think) and I'm sure that Windows has some equivalent library functions.

I tried to simplify it and focus on the main problem. I need to get that working.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.