Now this is just a little test, and part of a school assignment. In my code printf is not printing at least to me being able to see it. Is this a result of the thread not functioning? The print line works outside of the thread. Thank you for any help.
I am new to threading in c.
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", arg);
pthread_exit(0);
}
int main(int argc, char* argv[]){
int i=1;
while(argv[i]!=NULL){
pthread_t thread;
pthread_create(&thread, NULL, threadServer,argv[i]);
i++;
}
In your code, the parent thread of execution that created another thread finishes execution without waiting for its child threads to finish. And threads, unlike processes, once the parent thread terminates, all its child threads of execution terminate as well.
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", (char*)arg);
pthread_exit(0);
}
int main(int argc, char* argv[]){
int i=1;
while(argv[i]!=NULL){
pthread_t thread;
pthread_create(&thread, NULL, threadServer, argv[i]);
i++;
pthread_join(thread, NULL);
}
}
Doing this will allow the thread created to run, until it finishes execution. The pthread_join will wait for the thread to complete its execution and then move ahead.
EDIT
As people did mention in the comments, it is probably worthless trying to spawn a single thread and joining it immediately, making it no better than a single thread of execution. Hence, for the sake of experimentation, the code can be modified as follows:
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
void *threadServer(void *arg)
{
printf("This is the file Name: %s\n", (char*)arg);
}
int main(int argc, char* argv[]){
int i = 1;
pthread_t thread[argc - 1];
while(i < argc)
{
pthread_create(&thread[i-1], NULL, threadServer, argv[i]);
i++;
}
for (i = 0; i < argc - 1; ++i)
{
pthread_join(thread[i], NULL);
}
}
Related
// The thread of the periodic task is running in an infinite loop. I have included a flag and sleep(), so that it executes only for a certain time and then goes to sleep. But, after the modification, I am not getting the output "executing thread" at all. Please suggest, how to modify the use of the sleep function so that I get the output "executing thread" for the time and then it goes to sleep.//
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
int exitflag=0;
struct task_spec_struct
{
char task_type;
int period,r_min,r_max;
}s1;
int gen_rand(int a, int b)
{
srand(time(NULL));
int x = a+(rand()%(b-a));
return x;
}
//task body to utilize CPU to perform computations
void* periodic_task(void* arg)
{
struct task_spec_struct *arg_struct = (struct task_spec_struct*) arg;
int rand_num = gen_rand(arg_struct->r_min, arg_struct->r_max);
while(1)
{
int i, j=0;
for(i=0; i<rand_num; i++)
{
j=j+i;
}
if (exitflag==1)
{
pthread_exit(0);
}
usleep((arg_struct->period)*1000);
printf("Executing thread1");
}
//pthread_exit(0);
}
int main(int argc, char **argv)
{
int num_args = argc-1;
// Creating pthread for periodic task ( runs Thread function to run periodically)
// printf("\nGive task with specifications:");
s1.task_type= 'P';
s1.period= 300;
s1.r_min= 400;
s1.r_max= 500;
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, periodic_task, &s1);
int ret=sleep(3);
if (ret==0)
{
exitflag=1;
}
pthread_join(&tid, NULL);
}
printf does not flush by default unless you end the string with a newline character. See Why does printf not flush after the call unless a newline is in the format string?.
You are not seeing the output because the buffer is not being flushed. Either add a new line character, or call fflush on stdout.
Hey so I'm trying to create a multithreaded program. The first thread takes in input from std in and stores it in a minheap. The second thread... well for now, all it does is print "sequencer thread works" and nothing else because it doesn't run properly.
Both threads are detached, so they should run simultaneously, and yet for some reason the second thread doesn't run until the first exits. Is it something simple I am overlooking? I'm new to multithreading.
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/time.h>
#include "MinHeap.h"
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* readerthread(MinHeap minheap, char eventlist[], char timestamp[])
{
char buffer[100];
char input;
int ret, len, fd;
while(1)
{
char *choice;
choice = malloc(50*sizeof(char));
fgets(choice, 50, stdin);
printf("choice = : %s", choice);
if(checkTimestamp(choice)==0)
{
pthread_mutex_lock(&mutex);
addElement(&minheap, choice);
pthread_mutex_unlock(&mutex);
}
free(choice);
printf( "min of minheap: %s\n", getMin(&minheap));
}
void* sequencerthread()
{
printf("sequencer works\n");
fflush(stdout);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
if (argv < 2)
{
printf("not enough arguments. exiting...\n");
return 1;
}
char timestamp[50];
char event[50];
char eventlist[sizeof(char)+170];
int i;
char nowtimestamp[] = "2400/001/00/00/00";
MinHeap minheap;
initializeMinHeap(&minheap, intCompare, sizeof(char)*50);
strcpy(timestamp, argv[1]);
strcpy(event, argv[2]);
pthread_t ignore1, ignore2;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_create(&ignore1, &attr, readerthread(minheap, eventlist, nowtimestamp), 0);
pthread_create(&ignore2, &attr, sequencerthread, 0);
pthread_attr_destroy(&attr);
pthread_exit(0);
return (EXIT_SUCCESS);
}
This line is the problem:
pthread_create(&ignore1, &attr, readerthread(minheap, eventlist, nowtimestamp), 0);
You're calling readerthread on the main thread and passing its result to pthread_create. Since readerthread never returns, you never even get to the first call to pthread_create, let alone the second one.
You need to call it like this instead:
pthread_create(&ignore1, &attr, readerthread, &readerthread_args);
where readerthread_args is a struct encapsulating the arguments to pass to readerthread. You'll also need to change readerthread to take a single void * argument, cast it to the type of readerthread_args, and unpack the args.
You should have got a whole bunch of warnings from your compiler. Did you remember to turn them on?
I'm writing a C program using Pthreads that creates a child thread. After creating the child thread, the parent thread should ouput two messages: "parent:begin" then it should print "parent:done". Same for child thread "child:begin" and "child:done". I have to make sure that the main thread prints his second message before the spawned (child) thread does. I have to following implementation but it only prints in the wrong order. I assume I should use flags. Any help would be appreciated.
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
volatile int done = 0;
void *child(void *arg) {
printf("child\n");
done = 1;
printf("child:done");
return NULL;
}
int main(int argc, char *argv[]) {
printf("parent: begin\n");
pthread_t c;
pthread_create(&c, NULL, child, NULL); // create child
while (done == 0); // spin
printf("parent: end\n");
return 0;
}
If you want the parent to print done first, then you should have the child thread spin until the parent is done. (Right now the parent spins waiting for the child.) You should also use pthread_join to make sure the child is done before the main thread returns:
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
volatile int done = 0;
void *child(void *arg) {
printf("child: begin\n");
while (done == 0); // spin
printf("child: done\n");
return NULL;
}
int main(int argc, char *argv[]) {
printf("parent: begin\n");
pthread_t c;
pthread_create(&c, NULL, child, NULL); // create child
printf("parent: done\n");
done = 1;
pthread_join(c, NULL);
return 0;
}
On my machine I get this output:
parent: begin
parent: done
child: begin
child: done
At the moment done is accessed without any synchronization by both threads. Proper way is to signal the child that the parent has completed printing using a conditional variable. This leads to data race.
Moreover, main() thread complete the execution before the does. In that case, the whole process will die. You can either call pthread_join() or simply exit the main thread with pthread_exit().
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
volatile int done = 0;
void *child(void *arg) {
printf("child\n");
pthread_mutex_lock(&mutex);
while(done == 0)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
printf("child:done");
return NULL;
}
int main(int argc, char *argv[]) {
printf("parent: begin\n");
pthread_t c;
pthread_create(&c, NULL, child, NULL); // create child
pthread_mutex_lock(&mutex);
done = 1;
printf("parent: end\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
I have written a sample program to implement array of threads.There are two thread functions. Is there any way to define a fixed value of time (in seconds) after which all the threads will automatically stop?
Sample program:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void * threadFunc1(void * arg)
{
int id = *((int *) arg);
printf("Inside threadfunc2 for thread %d\n",id)
while(1);
}
void * threadFunc2(void * arg)
{
int i= *((int *)arg);
printf("Inside threadfunc2 for thread %d\n",i)
while(1);
}
int main(void)
{
pthread_t thread[10];
for(int i=0;i<10;i++)
{
pthread_create(&thread[i],NULL,threadFunc1,(void*)&i );
pthread_create(&thread[i],NULL,threadFunc,(void*)&i );
}
for (i=0;i<total;i++)
{
pthread_join(thread[i],NULL);
}
return 0;
}
Instead of waiting for the threads with pthread_join you could put your main thread to sleep, e.g with nanosleep. If you then quit your main without joining, your whole process will be killed.
No, there is not. Threads do not 'automatically stop'
This question already has an answer here:
Thread created (detached) never executed
(1 answer)
Closed 9 years ago.
I'm trying to compile and run the following code using Detached Threads in C Linux. The thing is that I want every thread to show me the corresponding printf from the handler *idThreadMethod and it doesn't show me anything! I tried using a printf before calling the pthread_create function and it shows it, but the problem should be inside the *idThreadMethod (handler function). The code:
//gcc detachedThreads.c -lpthread -o p
//./p 4
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int i;
void *idThreadMethod(void *args)
{
int pid;
pid = *((int *)args);
printf("\nI'm The Detached Thread %d\n", i);
printf("\nMy PID is: %d\n", pid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int quantityThreads, returnThread, pid;
pthread_t idThread[15];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
if(argc-1 < 1)
{
printf("\nSome arguments are missing\n");
return EXIT_FAILURE;
}
quantityThreads = atoi(argv[1]);
pid=getpid();
int *it = &pid;
for(i=0;i<quantityThreads;i++)
{
returnThread = pthread_create(&idThread[i],&attr,idThreadMethod,it);
if(returnThread == -1)
{
printf("\nThere is an error trying to create the thread\n");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
What could I do in order to show the printf messages from the *idThreadMethod function?
In main, use pthread_exit. Your main is exiting and thus the rest of your threads die, detached or not.
They're not showing because your main thread is exiting before they even get a chance to printf. As your threads are detached, you cannot use pthread_join to wait for them to do their thing, so you'll need some other form of synchronisation.
Seems to me, you don't really want detached threads at all....