Simple example for pthread_join deadlock - c

I am looking for a very simple example to demonstrate a deadlock using pthread_join; however, this is not trivial.
I started with this:
void* joinit(void* tid)
{
pthread_t* tid_c = (pthread_t*)tid;
int retval = pthread_join(*tid_c, NULL);
printf("In joinit: tid = %d, retval = %d \n", *tid_c, retval);
return NULL;
}
int main()
{
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, joinit, &thread2);
pthread_create(&thread2, NULL, joinit, &thread1);
pthread_join(thread2, NULL);
return 0;
}
But however, it says 'EINVAL' (invalid argument) because thread2 is not yet specified when pthread_create for thread1 is called.
Any ideas?

If you're just wanting to demonstrate that a pthread_join can cause a deadlock, you could do something similar to the following code:
#include <stdio.h>
#include <pthread.h>
void* joinit(void* tid)
{
printf("In %#x, waiting on %#x\n", pthread_self(), (*((pthread_t*)tid)));
pthread_join((*((pthread_t*)tid)), NULL);
printf("Leaving %#x\n", pthread_self());
return NULL;
}
int main(void)
{
pthread_t thread1 = pthread_self();
pthread_t thread2;
pthread_create(&thread2, NULL, joinit, &thread1);
joinit(&thread2);
return 0;
}
This will cause the main thread to wait on the spawned thread and the spawned thread to wait on the main thread (causing a guaranteed deadlock) without the need for extra locking primitives to clutter up what you are trying to demonstrate.
And to answer some of your questions more directly:
it says 'EINVAL' (invalid argument) because thread2 is not yet specified when pthread_create for thread1 is called.
... and from one of your comments ...
I tried this and it worked, but the problem is, it only works SOMETIMES because sometimes I get EINVAL again.
In your code, you call pthread_create consecutively to spawn the 2 threads:
pthread_create(&thread1, NULL, joinit, &thread2);
pthread_create(&thread2, NULL, joinit, &thread1);
In your joinit code, you grab the thread handle passed in to join on:
pthread_t* tid_c = (pthread_t*)tid;
int retval = pthread_join(*tid_c, NULL);
The reason this sometimes works and others you'll get EINVAL has to do with time slices allocated to each thread's context and sequencing. When the first pthread_create is called you will have a valid handle to thread1 after it returns but the handle to thread2 is not valid yet, at least not until the 2nd pthread_create is called.
To this, when a thread is created, the act of the thread coming "alive" (i.e. the thread function actually running) could take some extra time even though the thread handle returned is valid. In these instances, there is a chance one thread can execute more code than might be "expected". In your code, both pthread_create functions might happen to have been called in the time slice allocated for the main thread which could give each spawned thread enough "time" before hitting the pthread_join statement allowing tid_c to point to a valid handle; in the EINVAL case, pthread_create(&thread1, NULL, joinit, &thread2) was called and the spawned thread hit the pthread_join(*tid_c, NULL) before pthread_create(&thread2, NULL, joinit, &thread1) could give thread2 a valid handle (causing the error).
If you wanted to keep your code similar to how it is now, you would need to add a lock of some sort to ensure the threads don't exit or call anything prematurely:
#include <stdio.h>
#include <pthread.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void* joinit(void* tid)
{
/* this can be above the lock because it will be valid after lock is acquired */
pthread_t* tid_c = (pthread_t*)tid;
int retval = -1;
pthread_mutex_lock(&lock);
pthread_mutex_unlock(&lock);
printf("%#x waiting on %#x\n", pthread_self(), *tid_c);
retval = pthread_join(*tid_c, NULL);
printf("In joinit: tid = %d, retval = %d \n", *tid_c, retval);
return NULL;
}
int main()
{
pthread_t thread1;
pthread_t thread2;
/* get the lock in the main thread FIRST */
pthread_mutex_lock(&lock);
pthread_create(&thread1, NULL, joinit, &thread2);
pthread_create(&thread2, NULL, joinit, &thread1);
/* by this point, both handles are "joinable", so unlock */
pthread_mutex_unlock(&lock);
/* can wait on either thread, but must wait on one so main thread doesn't exit */
pthread_join(thread2, NULL);
return 0;
}
Hope this can help.

The main reason for your error is that you have two threads each waiting for the same thread to terminate because of the call to pthread_join in main. Another problem is that you don't ensure each thread correctly sees the other thread's ID.
Fix it like this:
#include <stdio.h>
#include <pthread.h>
pthread_t thread1;
pthread_t thread2;
pthread_mutex_t mutex;
pthread_cond_t cond;
int go = 0;
void* joinit(void* ptr)
{
// wait until both thread IDs are known
pthread_mutex_lock(&mutex);
while (go == 0)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
pthread_t* tid_c = *((pthread_t**) ptr);
printf("About to wait\n");
int retval = pthread_join(*tid_c, NULL);
printf("In joinit: tid = %d, retval = %d \n", *tid_c, retval);
// tell the other threads we're done
pthread_mutex_lock(&mutex);
go++;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main()
{
// setup synchronization
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thread1, NULL, joinit, &thread2);
pthread_create(&thread2, NULL, joinit, &thread1);
// tell the threads to go
pthread_mutex_lock(&mutex);
go = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
// wait for both threads to finish
pthread_mutex_lock(&mutex);
while (go != 3)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
return 0;
}

Related

pthread_detach doesn't change anything

I understand pthread_detach(pid) that: "storage for the thread thread can be reclaimed when that thread terminate" (as per http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_detach.html)
However, I understand that means that once the pid thread finishes executing, its memory will be freed, and we will not be able to run it again, or call join on it.
However, I tried the following code:
#include <stdio.h>
#include <pthread.h>
void* myFunction (void* arg)
{
printf("Hello World from thread!\n");
}
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, myFunction, NULL);
//pthread_join(tid, NULL);
int isDetached = -10;
isDetached = pthread_detach(tid);
printf("Is my thread detached: %d\n", isDetached);
int i;
for (i = 0; i<15; i++)
printf("%d\n", i);
pthread_create(&tid, NULL, myFunction, NULL);
pthread_join(tid, NULL);
for (i = 0; i<15; i++)
printf("%d\n", i);
return 0;
}
And I get the following:
If I understand correctly, since I did pthread_detach(tid), I should not be able to be able to do
pthread_create(&tid, NULL, myFunction, NULL);
pthread_join(tid, NULL);
after it, yet I did and it works perfectly. So, what is really the purpose of doing othread_detach(pid) if we can still run the thread and join it?
Thanks a lot!
pthread_detach simply tells your program that the current instance of tid will not join, (pthread_join) again, and frees up any pthread handles & objects on the tid instance.
Since you called pthread_detach if you try to pthread_join that thread it will not since it has been released and disposed of.
I've added the pthread_join to your code right after the detach call and you can see nothing happens as expected.
#include <stdio.h>
#include <pthread.h>
void * myFunction (void *arg)
{
printf ("Hello World from thread!\n");
}
int main ()
{
pthread_t tid;
pthread_create (&tid, NULL, myFunction, NULL);
//pthread_join(tid, NULL);
int isDetached = -10;
isDetached = pthread_detach (tid);
printf ("Is my thread detached: %d\n", isDetached);
/* ADDED FOR STACK OVERFLOW */
pthread_join (tid, NULL);
int i;
for (i = 0; i < 15; i++)
printf ("%d\n", i);
pthread_create (&tid, NULL, myFunction, NULL);
pthread_join (tid, NULL);
for (i = 0; i < 15; i++)
printf ("%d\n", i);
return 0;
}
I'm not sure what the confusion is but if you were expecting a different behavior when you called pthread_create a second time; note, this is really creating a fresh instance of tid for you. Therefore your second join call runs the thread.
pthread_t tid;
pthread_create(&tid, NULL, myFunction, NULL);
This creates a new thread and subsequent call topthread_detach(pid) detaches the thread created. Now
pthread_create(&tid, NULL, myFunction, NULL);
This creates a new thread and subsequently you have called a join which basically waits for the completion of the newly created thread, not for the one which has been detached.
You can check the code attached below. When you run this code the thread which has been detached is printing even after join is called i.e myfunc1 is still printing after the pthread_join.
#include <stdio.h>
#include <pthread.h>
void *myFunction2 (void *arg)
{
printf("Hello World from func2!\n");
}
void *myFunction1 (void *arg)
{
while(1) {
printf("Hello World from func1\n");
}
}
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, myFunction1, NULL);
//pthread_join(tid, NULL);
int isDetached = -10;
isDetached = pthread_detach(tid);
printf("Is my thread detached: %d\n", isDetached);
int i;
pthread_create(&tid, NULL, myFunction2, NULL);
pthread_join(tid, NULL);
for (i = 0; i<15; i++)
printf("%d\n", i);
return 0;
}
Your variable, tid, is not a thread. Your program does not start one thread two times, it creates two completely different threads.
The actual threads are objects that exist in the operating system. Your tid variable is just a "handle" that you can use to interact with a thread. Your second call to pthread_create(&tid,...) is re-using the handle variable, pointing it to a new, different thread.

create two task with preemption and priority

Putting it simple, I need two task, with one task having high priority, and other is low. when high priority. task is in execution low priority task should stop and after completion of high priority task , low priority task should Resume from previous state.
So need help..
This is example i used.
`#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int th1, th2;
/* Create independent threads each of which will execute function */
while (1)
{
th1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
if(th1)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",th1);
exit(EXIT_FAILURE);
}
th2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
if(th2)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",th2);
exit(EXIT_FAILURE);
}
printf("pthread_create() for thread 1 returns: %d\n",th1);
printf("pthread_create() for thread 2 returns: %d\n",th2);
}
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}
`
If you have a RTLinux (linux with real time extensions), you could simply define the priorities of the threads and let the system automatically suspend a low priority thread as soon as a higher priority thread starts. The referenced page show how to create a thread with a given priority (the lowest the highest):
pthread_attr_t attr;
struct sched_param param;
pthread_attr_init(&attr);
param.sched_priority = 1; // here priority will be 1
pthread_attr_setschedparam(&attr, &param);
pthread_create(&t1, &attr, &print_message_function, (void*) message1);
But you should not repeatedly start new threads in a loop, but put the loop in the function. To reproduce the example, print_message_function could be:
void print_message_function(void *ptr) {
char * message = ptr;
int i;
for (i=1; i<10; i++) {
printf("%s\n", message);
}
}
(here it will print 10 messages per thread)

Creating a new thread each time a method is called using pthread

I want to create a program that creates a new thread each time a specific method is called. Here is my working code so far:
#define NUMBER_OF_THREADS 3
pthread_t threads[NUMBER_OF_THREADS];
pthread_attr_t attr;
void *BusyWork(void *t)
{
int i;
long tid;
tid = (long)t;
printf("Thread %ld running...\n",tid);
// ...
printf("Thread %ld completed...\n",tid);
pthread_exit((void*) t);
}
void createNewThread(int number){
printf("running createNewThread(%d)\n", number);
pthread_t tid;
int rc = pthread_create( &tid, &attr, BusyWork, (void *) (long)number);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
int main(int argc, char *argv[]) {
int i, rc;
//Set up thread attributes
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
//Arbitary amount of calls (My real program will call the createNewThread() funcion multiple unkown amount of times)
createNewThread(15);
createNewThread(27);
createNewThread(62);
createNewThread(500);
createNewThread(8864);
createNewThread(99999);
//Free attributes
pthread_attr_destroy(&attr);
//Wait for other threads still running
// HOW CAN I DO THIS????
/*for (i=0; i< NUMBER_OF_THREADS; i++){
rc = pthread_join( ??? , NULL); //TODO
if (rc){
printf("ERROR: return code from pthread_join() %d\n", rc);
exit(-1);
}
printf("Main: completed join with thread %d\n", i);
}*/
printf("Main: program completed. Exiting.\n");
pthread_exit(NULL); // (?) Is this part nessassary as we are on the main thread and soon to exit the program
return 0;
}
However as you can see in my code there is a few issues! For example, how can I wait for all processes to complete for the code I am using, as I am not keeping track of the thread number. Also when a thread "BusyWork" is done it does not clean up after it self and left as an orphan process.
One idea I had was to use a vector to keep track of each thread number and then use that for the final join at the end of main. However the problem with that is the array list can easily get very large and will never shrink even though a thread is complete.
Detach the threads, don't join them. Before you create a thread, increment a counter protected by a mutex. Right before a thread terminates, acquire the mutex and decrement the counter. Now you know all threads are done when the counter reads zero. You can use a condition variable to make the counter waitable if you like.

How to use this for killing array of threads?

This code worked fine , but how to use it to kill for array of remaining threads?
#include<stdio.h>
#include<signal.h>
#include<pthread.h>
void *print1(void *tid)
{
pthread_t *td= tid;
pthread_mutex_t lock1=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock1);
printf("1");
printf("2");
printf("3");
printf("4\n");
printf("Coming out of thread1 \n");
sleep(2);
pthread_mutex_unlock(&lock1);
pthread_kill(*td,SIGKILL);//killing remaining all threads
return NULL;
}
void *print2(void *arg)
{
pthread_mutex_t *lock = arg;
pthread_mutex_lock(lock);
sleep(5);
printf("5");
sleep(5);
printf("6");
sleep(5);
printf("7");
sleep(5);
printf("8\n");
fflush(stdout);
pthread_mutex_unlock(lock);
return NULL;
}
int main()
{
int s;
pthread_t tid1, tid2;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
printf("creating Thread 1and 2 \n");
sleep(2);
pthread_create(&tid1, NULL, print1,&tid2);
pthread_create(&tid2, NULL, print2,&lock);
printf("Running Thread 1\n");
sleep(2);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
Comments: Please delete this and add some extra information about the code. The editor is not allowing me to edit the code.
here is an edited version of the code
along with some commentary
#include<signal.h>
#include<pthread.h>
void *print1(void *tid)
{
// should be in global space, so no need to pass
pthread_t *td= tid;
// this is a whole new mutex,
//should be in global space so other threads can access it
pthread_mutex_t lock1=PTHREAD_MUTEX_INITIALIZER;
// why bother with the mutex, it does nothing useful
pthread_mutex_lock(&lock1);
printf("1");
printf("2");
printf("3");
printf("4\n");
printf("Coming out of thread1 \n");
sleep(2);
pthread_mutex_unlock(&lock1);
pthread_kill(*td,SIGKILL);//killing remaining all threads return NULL;
// this exit is not correct, it should be this call:
// void pthread_exit(void *rval_ptr);
} // end function: print1
void *print2(void *arg)
{
// this should be in global memory so all threads using same mutex
pthread_mutex_t *lock = arg;
pthread_mutex_lock(lock);
sleep(5);
printf("5");
sleep(5);
printf("6");
sleep(5);
printf("7");
sleep(5);
printf("8\n");
fflush(stdout);
pthread_mutex_unlock(lock);
// this exit is not correct, it should be this call:
// void pthread_exit(void *rval_ptr);
return NULL;
} // end function: print2
int main()
{
int s;
// this should be in global memory
// so no need to pass to threads
pthread_t tid1, tid2;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
printf("creating Thread 1and 2 \n");
// why bother to sleep here?
sleep(2);
// in these calls, the last parm should be NULL
// and the related data should be in global memory
pthread_create(&tid1, NULL, print1,&tid2);
pthread_create(&tid2, NULL, print2,&lock);
// we are still in main, so this printf is misleading
printf("Running Thread 1\n");
// no need to sleep()
// as the pthread_join calls will wait for the related thread to exit
sleep(2);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
} // end function: main
However you want. There is no "one right way" to do this.
Probably the easiest way is to replace your calls to sleep with calls to a function that uses pthread_cond_timedwait and a predicate that causes the thread to call pthread_exit.
In psuedo-code, replace calls to sleep with this logic:
Compute the time to sleep until.
Lock the mutex.
Check if the predicate is set to exit, if so, call pthread_exit.
Call pthread_cond_timedwait.
Check if the predicate is set to exit, if so, call pthread_exit.
Check if the time expired, if not, go to stop 4.
And to terminate the threads, do this:
Lock the mutex.
Set the predicate to exit.
Call pthread_cond_broadcast.
Release the mutex.
Call pthread_join on the threads to wait until they've terminated.

Unexpected output in pthread

Hello for above code in thread it is displaying 0 (tid = 0) instead of 8... what may be the reason ? In PrintHello function I am printing threadid but I am sending value 8 but it is printing 0 as output
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *PrintHello(void *threadid)
{
int *tid;
tid = threadid;
printf("Hello World! It's me, thread #%d!\n", *tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t thread1,thread2;
int rc;
int value = 8;
int *t;
t = &value;
printf("In main: creating thread 1");
rc = pthread_create(&thread1, NULL, PrintHello, (void *)t);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
printf("In main: creating thread 2\n");
rc = pthread_create(&thread1, NULL, PrintHello, (void *)t);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
The actual object that holds 8 is value which is local to your main function so accessing after main has exited is not valid.
You don't wait for your child threads to finish before they attempt to access this local variable so the behaviour is undefined.
One fix would be to make your main wait for it's child threads before exiting using pthread_join.
(I've assumed that you've made a typo in your second call to pthread_create and meant to pass thread2 instead of thread1.)
E.g.
/* in main, before exiting */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

Resources