Segmentation Fault on multithreaded Producer Consumer C Program - c

// 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)

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.

Multi threading using p thread Linux problem

I have two functions, producer and consumer called by two p threads, but the while loop in the function is not running. Its a linux RT system. this is my code. im coding in eclipse.
#include <stdio.h>
#include"NIDAQmx.h"
#include <pthread.h>
#include "sts_queue/s_q.c"
#include <stdlib.h>
void *producer(void *ptr);// first function
void *consumer(void *ptr);// second function
TaskHandle taskHandle = 0;
int ret = 0;
int numChannels = 0;
int numRead;
float64 data[100];
int iret1, iret2;
pthread_t thread1, thread2;
int main(void) {
char *message1 = "Producer ended";
char *message2 = "consumer ended";
init();
ret = DAQmxCreateTask("task", &taskHandle);
ret=DAQmxCreateAIVoltageChan(taskHandle, "PXI1Slot2/ai0", "",
DAQmx_Val_Cfg_Default, -5, 5, DAQmx_Val_Volts, NULL);
ret=DAQmxCfgSampClkTiming(taskHandle, "", 1000, DAQmx_Val_Rising,DAQmx_Val_ContSamps, 100);
ret=DAQmxGetTaskAttribute(taskHandle, DAQmx_Task_NumChans, &numChannels);
ret=DAQmxStartTask(taskHandle);
iret1 = pthread_create(&thread1, NULL, producer,(void*) message1);// calling two threads
iret2 = pthread_create(&thread2, NULL, consumer,(void*) message2);// calling thread
}
void *producer(void *ptr) // enque function
{
char *message;
int i = 0;
int ret;
message = (char *) ptr;
while(i<1000)
{
//ret=DAQmxReadAnalogF64(taskHandle, 100, 10.0, DAQmx_Val_GroupByChannel, data,100 * numChannels, &numRead, NULL);
printf("task handle=%d\n",taskHandle);
printf("value of i=%d\n",i);
printf("Number of sample read%d\n",numRead);
printf("ret%d\n",ret);
sleep(.1);
i++;
}
ret=DAQmxStopTask(taskHandle);
ret=DAQmxClearTask(taskHandle);
printf("%s \n", message);
pthread_join(thread1, NULL);
return 0;
}
void *consumer(void *ptr) // deque function
{
char *message;
int k = 0;
int elements=0;
message = (char *) ptr;
while(k<1000)
{
printf("value ofk=%d\n",k);
sleep(.1);
k++;
}
printf("%s \n", message);
pthread_join(thread2, NULL);
}
Should i use pthread_exit or pthread-join?
how to use pthead_exit to exit first thread when while loop has exited?
now my console prints just this
task handle=-163491360
start0
value ofk=0
task handle=-163491360
value of i=0
Number of sample read0
ret0
logout
but actually value of i and k should go to 1000 and when it reaches 1000, while loop will stop and exit
Sometimes im getting this error too
pure virtual method called
terminate called without an active exception
Aborted
logout
You need to call pthread_join in the main function after creating thread1 and thread2. Otherwise, the main thread will terminate before thread1 and thread2 are completed.

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)

Threading in c and initgraph

This is a program I did but the problem I am facing is that its not giving any output. When I try to run one thread its running perfectly else it doesn't. I tried to output it directly in the terminal which is working perfectly but when I try to output in the window using initgraph its not working.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include<graphics.h>
struct myran
{
int x;
int y;
};
void *print_message_function( void *ptr );
main()
{
int gd=DETECT,gm=VGAMAX;
initgraph(&gd,&gm,NULL);
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int iret1, iret2;
struct myran a,b,c,d;
a.x=10;
a.y=10;
b.x=20;
b.y=20;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) &a);
if(iret1)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
exit(EXIT_FAILURE);
}
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) &b);
if(iret2)
{
fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
exit(EXIT_FAILURE);
}
printf("pthread_create() for thread 1 returns: %d\n",iret1);
//printf("pthread_create() for thread 2 returns: %d\n",iret2);
/* 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);
while(!kbhit())
;
closegraph();
exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr )
{
struct myran *ss;
ss=(struct myran *)ptr;
int `enter code here`x1,y1,x,y;
x1=ss->x;
y1=ss->y;
int i=0;
for(i=0;i<5;i++)
printf("%d \n", x1);
}

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