Multi threading using p thread Linux problem - c

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.

Related

Producer-Consumer solution runs but doesn't print

This is my current code for the Producer-Consumer problem. I compiled it and ran it but nothing is printed. The command line takes in 3 arguments: Sleep time, producer threads, consumer threads. I've tried setting the values as 5, 1, 1 respectively, the sleep timer works but I'm unsure about the rest.
Code for buffer.h:
typedef int buffer_item;
#define BUFFER_SIZE 5
Code for buffer.c:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include "buffer.h"
buffer_item buffer[BUFFER_SIZE];
void *producer(void *param);
void *consumer(void *param);
pthread_mutex_t mutex;
sem_t empty;
sem_t full;
int insert_item(buffer_item item)
{
do
{
wait(empty);
wait(mutex);
signal(mutex);
signal(full);
}while(1);
return 0;
}
int remove_item(buffer_item *item)
{
do
{
wait(full);
wait(mutex);
signal(mutex);
signal(empty);
}while(1);
return 0;
}
int main(int argc, char *argv[])
{
int sleepTime;
int producerThreads;
int consumerThreads;
int counter_1;
int counter_2;
if(argc != 4)
{
return -1;
}
sleepTime = atoi(argv[1]);
producerThreads = atoi(argv[2]);
consumerThreads = atoi(argv[3]);
srand((unsigned)time(NULL));
for(counter_1 = 0; counter_1 < producerThreads; counter_1++)
{
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, producer, NULL);
}
for(counter_2 = 0; counter_2 < consumerThreads; counter_2++)
{
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, consumer, NULL);
}
sleep(sleepTime);
return 0;
}
void *producer(void *param)
{
buffer_item item;
int randomTime;
int counter_1 = 0;
while(1)
{
randomTime = rand() % 1000 + 1;
sleep(randomTime);
item = rand();
if(insert_item(item))
{
fprintf(stderr, "Error.");
}
else
{
printf("Producer ID: %lu, Produced Item: %d\n", pthread_self(), item);
printf("The buffer now contains %d items\n", counter_1);
++counter_1;
}
}
}
void *consumer(void *param)
{
buffer_item item;
int randomTime;
int counter_2 = 0;
while(1)
{
randomTime = rand() % 1000 + 1;
sleep(randomTime);
if(insert_item(item))
{
fprintf(stderr, "Error.");
}
else
{
printf("Consumer ID: %lu, Consumed Item: %d\n", pthread_self(), item);
printf("The buffer now contains %d items\n", counter_2);
++counter_2;
}
}
}
So far I've tried declaring the tid separately, skipping sleep and join the threads, but it still doesn't print.
Your code can't possibly run, indeed it doesn't even compile.
Here's a list of issues that need to be addressed:
wait should be sem_wait
signal should be sem_post for semaphores
int sem_wait(sem_t *sem); and int sem_post(sem_t *sem); take the pointer to a semaphore
sem_wait(mutex) and sem_post(mutex) give something like "incompatible type for argument 1 of sem_wait", I guess you want to acquire and release the lock on the mutex like pthread_mutex_lock(&mutex) and pthread_mutex_unlock(&mutex)
in the consumer if(insert_item(item)): item is used uninitialized
still in the consumer you use insert_item instead of remove_item
Coming to the main question "I compiled it and ran it but nothing is printed", it doesn't print anything because producer and consumer call, respectively, insert_item and remove_item and are trapped inside infinite loops (e.g. while(1))

How do i properly call a function while creating pthread?

I am creating a pthread in the main function and calling another function called "PrintHello". the "PrintHello" function should print some messages. My threads are being created but i am guessing my function "PrintHello" isn't being called properly as the messages are not printing.
I have put another print command in "PrintHello" function and that is printing. That means the function is being called. but i can't figure out why the messages aren't printing.
char *messages[NUM_THREADS];
struct thread_data
{
int thread_id;
int sum;
char *message;
};
struct thread_data thread_data_array[NUM_THREADS];
void *PrintHello(void *threadarg)
{
printf("I am in PrintHello");
int taskid , sum;
char *hello_msg;
struct thread_data *my_data;
Sleep(1);
my_data = (struct thread_data *) threadarg;
taskid = my_data ->thread_id;
sum = my_data ->sum;
hello_msg = my_data ->message;
printf("Thread %d: %s Sum=%d\n", taskid , hello_msg , sum) ;
pthread_exit(NULL);
}
int main(int argc , char *argv[])
{
pthread_t threads[NUM_THREADS];
int *taskids[NUM_THREADS];
int rc, t, sum;
sum=0;
messages[0] = "English: Hello World!";
..............
messages[7] = "Latin: Orbis , te saluto!";
for(t=0;t<NUM_THREADS;t++)
{
sum = sum + t;
thread_data_array[t].thread_id = t;
thread_data_array[t].sum = sum;
thread_data_array[t].message = messages[t];
printf("Creating thread %d\n", t);
rc = pthread_create(&threads[t], NULL , PrintHello , (void *) &thread_data_array[t]);
//rc = pthread_create(&threads[t], NULL , PrintHello , NULL);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d \n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
The code should print out the hello messages.
I assume what's happening is your application is exiting before your threads have the chance to actually execute fully. Since you are storing each thread handle in the array of pthread_t threads[NUM_THREADS]; what you will need to do is upon creation a call to
pthread_join should be made which will allow the caller thread to be blocked until the thread has executed and returned. You can call pthread_join right after you call pthread_create or loop through all your handles and call pthread_join on each index in your array. If a call to pthread_join is made after the creation of each thread individually then a new thread will not spawn until the previous finishes. If you wish to execute them simultaneously then a loop after all the threads have been created would be the better option.
int main(int argc , char *argv[])
{
pthread_t threads[NUM_THREADS];
int *taskids[NUM_THREADS];
int rc, t, sum;
sum=0;
messages[0] = "English: Hello World!";
..............
messages[7] = "Latin: Orbis , te saluto!";
for(t=0;t<NUM_THREADS;t++)
{
sum = sum + t;
thread_data_array[t].thread_id = t;
thread_data_array[t].sum = sum;
thread_data_array[t].message = messages[t];
printf("Creating thread %d\n", t);
rc = pthread_create(&threads[t], NULL , PrintHello , (void *) &thread_data_array[t]);
//rc = pthread_create(&threads[t], NULL , PrintHello , NULL);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d \n", rc);
exit(-1);
}
}
for(int index = 0; index < NUM_THREADS; ++index){
pthread_join(threads[index],NULL);//Wait for execution of each thread
}
}
You also don't need to call pthread_exit in your main. Typically that should be called in the thread you wish to terminate early where the value passed into pthread_exit can be retrieved from the second argument of pthread_join
Sorry for the late reply. I should have mentioned that i am using Windows. Anyway, i found out the problem. It is happening because of the "sleep" argument. For windows apparently it is different. so i changed my sleep argument to Sleep(1000), which apparently means 1 second in windows and that solved my problem. Thank you for all the replies.

segmentation fault in multithread program

I'm trying to write a program that uses 3 threads with a shared memory. the shared memory is an array with 101 values. the first value shared memory[0](initialized to 0) is status value which determines which operation should take place. the three threads do
The first one should fill the shared memory array with 100 random values. and set the status value to 1.
The second should print the product of the 100 random values (from index 1 to 100). and set the status value to 2.
The third should print the average of the 100 random variables. and set the status value to 0. so that thread one fill the shared memory with different random variables.
this is my code
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
unsigned int product=0;
float avg=0;
int* shared_memory;
int status=0;
void productAllThread();
void averageAllThread();
void *parentProcess();
void *prodAll();
void *avgAll();
void initializeArray();
int main(int argc, const char * argv[])
{
time_t t;
key_t key = 9876;
// Create shared memory area
int shm_id = shmget(key, sizeof(int)*101, IPC_CREAT | 0666);
// initialize the random variable
srand((unsigned) time(&t));
// Create shared memory
shared_memory=shmat(shm_id, NULL, 0);
//create threads
pthread_t tid1, tid2, tid3;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid1, &attr, parentProcess, NULL);
pthread_create(&tid2, &attr, prodAll, NULL);
pthread_create(&tid3, &attr, avgAll, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
return 0;
}
void initializeArray() {
shared_memory[0]=0;
status=shared_memory[0];
int i= 0;
printf("Initial Array:{");
for(i=1; i<100; i++)
{
shared_memory[i]=rand()% 50;
printf("%d,", shared_memory[i]);
}
printf("}\n");
}
void *parentProcess()
{
while(1)
{
status=shared_memory[0];
if(status==0) {
// initialize array
initializeArray();
shared_memory[0]=1;
} else {
sleep(10);
}
}
}
void averageAllThread() {
while(1) {
status=shared_memory[0];
if(status==2)
{
avgAll();
wait(NULL);
printf("Avg:%.2f\n", avg);
shared_memory[0]=0;
} else {
sleep(5);
}
}
}
void productAllThread() {
while(1){
status=shared_memory[10];
if (status==1)
{
prodAll();
wait(NULL);
printf("Sum:%d\n",product);
shared_memory[0]=2;
} else {
sleep(5);
}
}
}
void *prodAll()
{
while(1){
int i=1;
product=0;
for(i=1; i<100; i++)
{
product=product+shared_memory[i];
}
}
}
void *avgAll()
{
while(1){
int i=0;
avg=0;
for(i=1; i<100; i++)
{
avg=avg+shared_memory[i];
}
avg=avg/100;
}
}
when I run it in the terminal, it gives me this error
"Segmentation fault: 11"
what might cause this type of errors? If this error is fixed will the program work fine to do the job I want it to do?
I found a few problems in your program:
You are calling the wrong functions to start your threads:
pthread_create(&tid1, &attr, parentProcess, NULL);
pthread_create(&tid2, &attr, prodAll, NULL);
pthread_create(&tid3, &attr, avgAll, NULL);
Should be:
pthread_create(&tid1, &attr, parentProcess, NULL);
pthread_create(&tid2, &attr, productAllThread, NULL);
pthread_create(&tid3, &attr, averageAllThread, NULL);
You have a few calls to wait() like this:
wait(NULL);
You should remove all of them.
The while loops in avgAll() and prodAll() should be removed since there are already while loops in the callers of those functions.
The call to srand() should be made from parentProcess() otherwise it might not affect the rand() calls in that 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);
}

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)

Resources