As far as threading goes, I'm most familiar with the pthreads implementation, which is fully portable across dozens of platforms.
here's a basic example;
Code:
#include <pthread.h>
#include <iostream>
using std::cout;
using std::endl;
// this is the function that executes when the threads are created.
// it takes a void* parameter, which could just as easily be any type of pointer
void* thread_proc(void* ptr)
{
cout << "String passed to thread was: " << (char*)ptr << endl;
pthread_exit(NULL);
}
int main(void)
{
// declare two pthread_t objects to keep track of the threads
// as far as I know, they are just integer types
pthread_t thread1, thread2;
// two strings to send to the threads.
char* str1 = "This is thread1.";
char* str2 = "This is thread2.";
// create the threads
pthread_create(&thread1, NULL, thread_proc, str1);
pthread_create(&thread2, NULL, thread_proc, str2);
cout << "In main thread." << endl;
// wait for both threads to finish before continuing
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// done so return
return 0;
}
if you install the pthreads libraries for windows, you can use code like this in your windows apps.
One thing you need to remember is that a thread cannot be started with a non-static class member function. It's not a big deal though, as you can create a static member function that takes a pointer that it will use as "this".
This example should get you started, and I know lots of people here on this board are familiar with pthreads, so finding help should be no problem if you run into trouble. For further reading, I suggest
http://www.yolinux.com/TUTORIALS/Lin...ixThreads.html. it is specifically for linux, but all of the code that is not platform-specific will work on windows as well if you have pthreads installed.
here is an example of how you might make a thread class that will spawn a new thread for each object that is created:
Code:
class function_object
{
public:
void operator () (void* ptr)
{
cout "string: " << ptr << endl;
}
};
template<class T>
class Thread
{
public:
Thread(void* param)
{
pthread_create(&thread, NULL, Thread::thread_proc, param);
pthread_join(thread, NULL);
}
static void* thread_proc(void* ptr)
{
T* obj = new T();
obj(ptr);
delete obj;
pthread_exit(NULL);
}
private:
pthread_t thread;
};
// To create a new thread, you would use the following code:
Thread<function_object>* mythread = new Thread<function_object>(some_pointer);