Hi Guys,
So I'm trying to experiment with threads, though I'm running into some problems. Basically I'm trying to create multiple threads, where each thread is passed a different set of data. In my small example below, I'm starting off with a vector<string> of data. Each element of the vector is the data for each thread. The problem I'm having is that all threads seem to be receiving the LAST entries data. (As if all threads are sharing the same data...) For the time being, I want all threads to act independently..
Temp.cpp:
104 nmmgdsm40.ny.fw.gs.com|/home/hoffda/code> cat Temp.cpp
extern "C"
{
#include "pthread.h"
#include "Thread.h"
}
#include <iostream>
#include <vector>
#include "Temp.h"
using namespace std;
void manageThreads(vector<string> & temp);
int startSingleThread( char * params )
{
cout<<"In thread, param:"<<params<<endl;
return 0;
}
int main()
{
vector<string> a;
a.push_back( "FIRST");
a.push_back( "SECOND");
a.push_back( "THIRD");
manageThreads( a );
}
void manageThreads(vector<string> & temp)
{
unsigned int size = temp.size();
int * status = new int[size];
pthread_t * thread = new pthread_t[size];
for ( unsigned int i=0;i < size;i++)
{
char myString[1000];
strcpy( myString, temp[i].c_str() );
pthread_create( &thread[i], NULL, myTest, &myString);
}
for ( unsigned int i=0;i < size;i++)
pthread_join(thread[i], (void **) &status[i] );
cout<<"Deleting threads and status..."<<endl;
delete [] thread;
delete [] status;
}
Temp.h:
int startSingleThread( char * param );
Thread.h:
#include "stdio.h"
#include "Temp.h"
void * myTest(void * arg)
{
char * test = (char * ) arg;
printf( "Starting thread with param:'%s'\n", test );
return (void *) startSingleThread( test );
}
CC Temp.cpp -lpthread -o Temp
./Temp
Starting thread with param:'THIRD'
Starting thread with param:'THIRD'
Starting thread with param:'THIRD'
In thread, param:THIRD
In thread, param:THIRD
In thread, param:THIRD
Deleting threads and status...