#include #include #include #include #include #include #include "squarethis.h" using namespace std; int main (int argc, char **argv) { srand (time(NULL)); id = new int[SIZE]; squares = new int[SIZE]; th = new pthread_t [SIZE]; //array of threads for (int i=0; i < SIZE; i++) { id[i] = i; pthread_create (&th[i],nullptr,squareself,&id[i]); /* the first argument is a pointer to a thread (actually a thread type) th is an array of threads. th[i] is one specific thread in the array &th[i] is a pointer to that specific thread The second argument defines the "attributes" for the thread. A null pointer indicates the default attributes, which is all we are really going to use. The third argument is a function pointer to the method the thread will run. It must be a method takes one void * argument and returns void * The fourth argument is the parameter that will be passed to the method specified in the third argument */ } for (int i=0; i < SIZE; i++) pthread_join (th[i],nullptr);//waiting until the threads die //the first argument is the thread we're waiting for //The second argument is where we put the return value of the thread (which is null in this case) for (int i=0; i < SIZE; i++) cout << squares[i] << endl; cout << endl; delete[] id; delete[] squares; delete[] th; return 0; } void *squareself (void * a) { //thread methods ALWAYS take a void * pointer and ALWAYS return a void * pointer //in this case they will take a memory location containing an integer I want to square //The method will square that integer and then return null //void * is a pointer to anything. It can point to an int or char or struct //or anything random and it works without casting. int t = 1+rand()%10; //get a random int between 1 and 10 sleep (t); int idnum = *(int *)a; squares[idnum] = idnum*idnum; // cout << "Squared " << idnum << endl; return nullptr; }