I have a program that is trying to use create and cancel through an implemented pool.
The creation is as follows:
int threadsNum=10;
while (created<threadsNum){
pthread_t newThread;
pthread_struct *st; //Open the thread that handle the deleting of the sessions timeout.
st = (pthread_struct*)malloc(sizeof(pthread_struct));
st->id = created;
st->t = newThread;
pthread_mutex_lock( &mutex_threadsPool );
readingThreadsPool[created] = st;
pthread_mutex_unlock( &mutex_threadsPool );
if((threadRes1 = pthread_create( &newThread, NULL, pcapReadingThread, (void*)created)))
{
syslog(LOG_CRIT, "Creating Pcap-Reading Thread %d failed.",created);
printf( "Creating Pcap-Reading Thread %d failed.\n",created);
exit(1);
}
syslog(LOG_INFO, "Created Pcap-Reading Thread %d Successfully.",created);
created++;
}
Later I try to cancel them and restart them :
pthread_t t;
pthread_struct* tstr;
int i;
pthread_mutex_unlock( &mutex_threadsPool );
//first go on array and kill all threads
for(i = 0; i<threadsNum ; i++ ){
tstr = readingThreadsPool[i];
if (tstr!=NULL){
t = tstr->t;
if (pthread_cancel(t)!=0){
perror("ERROR : Could not kill thread");
}
else{
printf("Killed Thread %d \n",i);
}
}
}
So far so good, but the only problem is that the output is
Error : Could not kill thread : Illegal Seek
Killed Thread 1
Killed Thread 2
Killed Thread 3
Killed Thread 4
Killed Thread 5
Killed Thread 6
Killed Thread 7
Killed Thread 8
Killed Thread 9
Why doesn’t it kill the thread in the 0 index as well?
And I couldn’t find anything about Illegal Seek..
Thanks for your help people
Thanks
The problem is that
newThreadis being used before it is initialized:but
newThreaddoes not receive a value until after the successful invocation ofpthread_create(). It appears thatnewThreadvariable is retaining its previous value on subsequent iterations of the loop, which results in the correct cancelling of all threads except for last thread started as its id is never inserted into thereadingThreadsPoolarray.You need to populate the
st->tmember after the call topthread_create().As the code currently stands, it is possible for an entry to be inserted into the
readingThreadsPoolarray even though it is not actually a thread yet. Put the insertion logic after the call topthread_create():or if the
pcapReadingThread()function accessesreadingThreadsPooland expects an entry for itself (which I think might be the case due tocreatedbeing passed) then enclose thepthread_create()inside the lock ofmutex_threadsPool.