Game Development Community

Threading

by James Novosel · in Torque 3D Professional · 04/11/2016 (4:20 pm) · 2 replies

I need to start a thread in order to perform an operation.

This link works like a charm:
www.garagegames.com/community/blogs/view/20954

But what I really need is a way to pass a string into that thread.
This (in the example) will not do it: mThread = new Thread((ThreadRunFunction)launchThread, this);

There is an alternate method call that appears to allow passing of a parameter (themessage string I need to pass):
mThread = new Thread((launchThread,themessage,true,false));

But I can't for the life of me get that working.

Does anyone have an example of passing a parameter into the thread ?

Thanks in advance !

#1
04/11/2016 (4:53 pm)
All you have to do is modify ThreatTest class to add more member variables that you want to pass to the thread and can access them via the passed this as ThreadTest* pThis in ThreadTest::launchThread() function.

Here's an example:
#ifndef _PLATFORMTHREAD_H_
	#include "platform/threads/thread.h"
#endif

class ThreadTest : public SimObject
{
	typedef SimObject Parent;
	char *mString;

public:
	ThreadTest();
	~ThreadTest();

	Thread* mThread;
	static void launchThread(void* data);
	
	void processThread();
	
	DECLARE_CONOBJECT(ThreadTest);
	
};

And then slight modification to just two of the functions:
//..
ThreadTest::ThreadTest()
{
	mString = "Some test string text data.";

	mThread = new Thread((ThreadRunFunction)launchThread, this);
	mThread->start();
}

//..

void ThreadTest::processThread()
{
// >>> Implement your own code here!
	Con::printf("ThreadTest mString value is \"%s\"", mString);

	for(int i = 0 ; i < 1000 ; i++) // Create 1000 random points
	{
		Con::printf("ThreadTest Random Points (%f, %f, %f)", mRandF(0, 1000), mRandF(0, 1000), mRandF(0, 1000)); // Con::printf isn't actually threadsafe but works for the example
		// Platform::sleep(10); // If we want to throttle this thread by 10ms
	}
// <<< Implement your own code here!
}

#2
04/12/2016 (5:15 pm)
Thanks Nathan !
Thats exactly what I needed.
(too simple actually, coding this from a C# background and learning C by trial and error)