It’s sometimes hard to find a good example of working with threads in C++. Thus, in the course of implementing a very simple working example I decided it wouldn’t hurt to post what I came up with.
The following code will spawn 2 threads (for a total of three program threads), and calculate 40 iterations of the fibonacci_number function. You can make it spawn more threads via threads, as well as change the number of iterations via the iterations < 40 condition.
I also have some test code at the top of our threadfunc method for variable passing. Any time you start working with threads you need to be aware of the pitfalls that come with data access, and this is something I very much look forward to learning more about.
Please note the code was run on Linux, specifically Ubuntu 10.04. You’ll need the g++ compiler and other dev libs via individual packages (e.g. libc6-dev) or <sudo aptitude install build-essential>.
Also, as the in-code comment below states, you need to include the Posix Threads library in the LinkerĀ Properties of the project properties area when using NetBeans, I’m not sure about other IDE’s.
-
#include <unistd.h>
-
#include <pthread.h>
-
#include <stdlib.h>
-
#include <iostream>
-
#include <string>
-
-
// We need to include POSIX threads in the linker properties (project settings)
-
-
using namespace std;
-
-
int fibonacci_number(int num)
-
{
-
switch(num)
-
{
-
case 0:
-
case 1:
-
return 1;
-
default:
-
return fibonacci_number(num-2) + fibonacci_number(num-1);
-
};
-
}
-
-
void* parallel_threadfunc(void *arg) {
-
sleep(1);
-
std::cout << "Thread called…" << arg << endl;
-
-
// we cannot get the direct value of our variable, I have to create a
-
// new pointer and cast the *arg to that (an int pointer), then dereference it.
-
int * l;
-
l = (int*)arg;
-
std::cout << "Value Passed…" << *l << endl;
-
-
// loop
-
int iteration = 1;
-
while(iteration < 40){
-
int value = fibonacci_number(iteration);
-
iteration++;
-
std::cout << "Itteration#…" << iteration << endl;
-
}
-
-
// exit
-
pthread_exit(NULL);
-
}
-
-
int main() {
-
-
int i;
-
int threads = 2;
-
-
int x[] = {0,1,2,3,4,5,6,7,8,9,10};
-
-
// thread attributes
-
pthread_attr_t attr;
-
pthread_attr_init(&attr);
-
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
-
-
pthread_t t[threads];
-
-
for (i = 0; i < threads; ++i) {
-
pthread_create(&t[i], &attr, parallel_threadfunc, (void*)&x[i]);
-
}
-
-
cout << x << endl;
-
-
int n;
-
cout << "Enter a number to quite the program:" << endl;
-
cin >> n;
-
-
return (EXIT_SUCCESS);
-
}