create two task with preemption and priority - c

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)

Related

why the order of my output doesn't change even if i change my pthread_join() place

why do I get the same output order when pthread_join( thread3, NULL); comes before pthread_join( thread1, NULL);
and when:
pthread_join( thread1, NULL); comes before pthread_join( thread3, NULL);
I know that pthread_join() waits for the thread to terminate and it worked on thread 2 but why it doesn't work here like I waited for thread 3 to terminate but it still terminates after thread 1 terminate.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * print_message_function( void *ptr );
void * do_something_else( );
void * a_new_function();
int main()
{
pthread_t thread1, thread2,thread3,thread4;
char *message1 = "Thread 1 is running ";
char *message2 = "Thread 2";
int iret1, iret2,iret3;
void * (*f_ptr)();
f_ptr = do_something_else;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, f_ptr/*do_something_else*/, NULL);
pthread_join( thread2, NULL);
iret3 = pthread_create( &thread3, NULL,a_new_function , NULL);
pthread_join( thread3, NULL); //--------------here-------------------------------
pthread_join( thread1, NULL); //---------------here-------------------------------
return 0;
}
void * print_message_function( void *ptr )
{
int i;
for(int i=0; i < 1; i++)
printf("%s \n", (char *)ptr);
}
void * a_new_function(){
int a;
int b;
int c;
a=5;b=7;
c=b+a;
printf ("the value of c =%d\n",c);
return 0;
}
void * do_something_else( )
{
int i;
for(int i=0; i < 1; i++)
printf("%s \n", "this is do_something_else function");
}
the output in both ways is:
**this is do_something_else function
Thread 1 is running
the value of c =12**
Pthread_join does not affect the scheduling of the thread that you are joining with; really it is just a way to cleanup resources and retrieve exit status.
In your example, the only dependency is that thread 2 will complete before thread 3, since you do not create thread 3 until you have joined thread 2.
This has no effect on thread 1; and the order of the final joins is irrelevant.
"Waiting for X" is just waiting until X happens. "Waiting for Y" is just waiting until Y happens. Until either X or Y happens, there is no difference between waiting for X and waiting for Y. It's not clear why you think it makes any difference which thread you wait for. Waiting has no effect on the things that you are waiting for. It just waits for them to finish.

Can not set low priority in using pthread_setschedparam() for pthreads

I was trying to set a low priority [ priority = 10 ], in Linux using
pthread_setschedparam()
However, the accepted values I get from function
sched_get_priority_{min|max}() is 0-99.
If I give 1, I get priority as -2.
If I give 90, I get priority as -90.
But I want to get priority 10.
Code is given below. Is there a way to assign low priority to a thread.
[ NOTE - I tried also a setpriority, but that doesn't work in my case, since I need to assign priorities from the main thread ]
#include <pthread.h>
#include <errno.h>
#include <string.h>
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int iret1, iret2;
struct sched_param sch_params;
//sch_params.sched_priority = 5;
sch_params.sched_priority = 10;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
if(iret1)
{
printf("Error - pthread_create() return code: %d\n",iret1);
exit(EXIT_FAILURE);
}
if(pthread_setschedparam(thread1, SCHED_RR, &sch_params)) {
printf( "Failed to set thread's priority : %s \n",strerror(errno));
} else {
printf( "thread priority is set properly: \n");
}
pthread_join( thread1, NULL);
exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
while (1) {
printf("%s \n", message);
sleep(1);
}
}

Simple example for pthread_join deadlock

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;
}

Segmentation Fault on multithreaded Producer Consumer C Program

// This is the multi-threaded code for a producer Consumer program ,it runs //successfully completion of both the threads , but receives a Segmentation error just //before thread join , I am not really able to figure it out
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
void* writer_function ();
void* reader_function ();
char buffer[9];
sem_t empty_buffers;
sem_t full_buffers;
int main()
{
pthread_t thread1, thread2;
//const char *message1 = "Thread 1";
//const char *message2 = "Thread 2";
int iret1, iret2;
sem_init(&empty_buffers,0,8);
sem_init(&full_buffers,0,0);
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL,writer_function, NULL);
if(iret1)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
exit(EXIT_FAILURE);
}
iret2 = pthread_create( &thread2, NULL, reader_function(), NULL);
if(iret2)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
exit(EXIT_FAILURE);
}
// Runs Successfully ,and segmentation fault here
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("pthread_create() for thread 1 returns: %d\n",iret1);
printf("pthread_create() for thread 2 returns: %d\n",iret2);
sem_destroy(&empty_buffers);
sem_destroy(&full_buffers);
/* 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. */
printf("This marks the end and the threads to be joined \n ");
//exit(EXIT_SUCCESS);
return 0;
}
void* writer_function ()
{
int i ;
for (i = 0 ; i < 40 ; i++){
char c = (i + 66);
sem_wait(&empty_buffers);
buffer[i%8] = c;
sem_post(&full_buffers);
printf(" WRITER:the letter Written is %c\n", c);
}
}
void* reader_function ()
{
int i ;
for (i = 0 ; i < 40 ; i++){
sem_wait(&full_buffers);
char c = buffer[i%8];
sem_post(&empty_buffers);
printf("READER:the letter Received is %c\n", c);
}
}
change:
iret2 = pthread_create( &thread2, NULL, reader_function(), NULL);
to
iret2 = pthread_create( &thread2, NULL, reader_function, NULL);
add return NULL; for both functions reader_function, writer_function after loop and change their header from writer_/reader_function() to writer_/reader_function(void *args)

Creating Dynamic Threads in C

How do we create multiple thread during runtime in C programming language?
If we need to create same amount of thread as specified by the user how do we do it?
On Linux use pthreads
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
int main(int argc, char *argv[])
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
/* 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);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}
Check _beginthread for Windows and posix threads for linux
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
void *print()
{
printf("\nThread Created");
}
int main()
{
int ch,i;
pthread_t *t;
printf("Enter the number of threads you want to create : ");
scanf("%d",&ch);
t=(pthread_t *)malloc(ch * sizeof(pthread_t ));
for(i=0;i<ch;i++)
{
pthread_create(&t[i],NULL,print,NULL); //Default Attributes
}
for(i=0;i<ch;i++)
{
pthread_join(t[i],NULL);
}
}
This is the most basic code for creating threads during runtime in Linux OS using pthread library.
pthreads

Resources