The point of threads is to be able to run multiple blocks of code at once. The first thing I think of when this possibility comes into my head is having two infinite loops running at once. Before I tried to get this working with two threads, I tried to get it to work with one, with no success.
So I have a thread like this:
void *myThread(void *args) {
sleep(0.1);
while (1) {
}
return NULL;
}
And I am creating the thread like so:
pthread_t thread_id;
printf("Before Thread\n");
pthread_create(&thread_id, NULL, myThread, args);
pthread_join(thread_id, NULL);
printf("After Thread\n");
When I run this, "After Thread" does not print! Why is this happening? This makes no sense to me.
Because pthread_join(thread_id, NULL); waits for the thread to finish. And a thread running a while (1) {} loop will never finish.
Related
I'm new to threading in C and was messing around in an attempt to learn about it. I compiled and executed the (very basic) code below:
void *thread(void *vargp);
int main(int argc, char **argv) {
pthread_t tid1, tid2;
printf("Hello from the main thread.\n");
printf("Creating thread 1.\n");
pthread_create(&tid1, NULL, thread, NULL);
printf("Creating thread 2.\n");
pthread_create(&tid2, NULL, thread, NULL);
printf("Main thread is going to wait on peer threads.\n");
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("Peer threads have completed.\n");
return EXIT_SUCCESS;
}
void *thread(void *vargp) {
pthread_t tid = pthread_self();
printf("Hello from thread %u.\n", (unsigned int)tid);
return NULL;
}
I expected the output to be...
Hello from the main thread.
Creating thread 1.
Hello from thread [number].
Creating thread 2.
Hello from thread [number].
...
But instead, it was:
Hello from the main thread.
Creating thread 1.
Creating thread 2.
Main thread is going to wait on peer threads.
Hello from thread 3067947840.
Hello from thread 3076340544.
...
Why was the output in this order? Did the two threads wait until the join function to execute or did they just happen to take that long? Do threads need to be joined to the main thread in order to print output to the console?
Thanks for explaining this to me!!
You have only created threads 1 and 2 in order. But they'are necessarily executed in that order. The execution order is depends on how they're scheduled, number of processors available, etc.
So you could see the output from the two threads in any order.
If you would like to the output in "order", you could wait for first thread to complete before starting the next one.
printf("Creating thread 1.\n");
pthread_create(&tid1, NULL, thread, NULL);
pthread_join(tid1, NULL);
printf("Creating thread 2.\n");
pthread_create(&tid2, NULL, thread, NULL);
pthread_join(tid2, NULL);
This, of course, defeats the purpose of mutli-threading as only one thread ever does anything useful.
The ordering can be achieved in many ways. A simple way could be to use a semaphore.
Hi I am trying to make 3 thread that will print different messages multiple times. Then sync them, so to print for example ONE TWO THREE ONE TWO THREE ONE TWO THREE... When I run the program sometimes it is not correct and I am not sure what I am doing wrong.
sem_t sema, semb, semc;
void *printone(void *arg)
{
printf("<ONE>");
sem_wait(&semc);
sem_post(&semb);
}
void *printtwo(void *arg)
{
printf("<TWO>");
sem_wait(&sema);
sem_post(&semc);
}
void *printthree(void *arg)
{
printf("<THREE>");
sem_wait(&semb);
sem_post(&sema);
}
main()
{
pthread_t th1,th2,th3;
int i;
sem_init(&sema,0,1);
sem_init(&semb,0,0);
sem_init(&semc,0,0);
for(i=0;i<10;i++){
pthread_create( &th1, NULL, printone, (void *) 1);
pthread_create( &th2, NULL, printtwo, (void *) 2);
pthread_create( &th3, NULL, printthree, (void *) 3);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
pthread_join(th3, NULL);
}
pthread_exit(NULL);
}
You seem to have a workable approach: each thread waits on one semaphore, and later posts another to let the next thread run. For that to work, however, each thread should wait for its semaphore before performing its work (i.e. print its message).
Additionally, it looks like your thread functions are using the wrong semaphores. For printone() to run first, it must wait on the semaphore that you initialize with value 1. For printtwo() to run next, it must wait on whichever semaphore printone() posts to. Similarly, for printthree().
As a secondary matter, if your thread functions are not going to use their argument, then it would be best to pass NULL as the third argument to pthread_create().
Trying to set up a small client-server program. However, I've noticed output from the second thread doesn't get out printed.
void *ClientRoutine(void *args){
printf("Client thread created\n");
pthread_exit(NULL);
}
int main(int argc, char *argv[]){
pthread_t client_thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (pthread_create(&client_thread, &attr, &ClientRoutine, NULL)) {
perror("Failed to create client thread");
exit(-1);
}
pthread_attr_destroy(&attr);
return 0;
}
If I printf something in the main thread, the client's output finally shows up. Can anyone explain why this is happening?
LE: as some of you have suggested, this does happen because the main thread exits early. However, according to this: What happens to a detached thread when main() exits?, the detached thread should continue execution even after main exits. Why does this happen?
Maybe you're destryoing the detached thread too early? If you just create the thread and then destroy it, you don't give printf even time to execute. Try to add some sleep time after the thread creation in main and you'll see the output.
When you add another printf in the main thread, you give the other thread time to execute before being destroyed.
This might happen when your main thread exits before the newly created one gets time to print. Can be solved if the main thread waits till the other thread has completed the action. Use pthread_join for this.
Try calling
pthread_join(client_thread, NULL);
before
pthread_attr_destroy(&attr);
When you add another print statement in main thread, it actually keeps the main thread alive for more duration.
when you create thread using thread_create and pass the function, does the function goes forever if there is infinite loop in the function?
eg
for(;;){
//dosomthing
}
Does the thread keep "do somthing" until the thread is destroyed or the program is finished?
Thanx
When you invoke thread_create() the thread that gets created will itself invoke the function you passed. So for example:
pthread_t thread1;
pthread_create(&thread1, NULL, thread_do, NULL);
will make a new thread and the new thread will run the function thread_do().
If now you have previously defined thread_do() as:
void* thread_do(){
for(;;){
// do something
}
return NULL;
}
then the thread will go to an endless loop indeed.
I'm working on an application for Linux in C which uses multiple threads. The threads which are spawned by the main function do most of the work, and therefore usually finish last. I'm seeing some strange behavior, and I believe it's due to the main thread terminating before the spawned threads have a chance to finish their jobs. Here's some sample code to illustrate what I'm talking about:
#define _POSIX_C_SOURCE 200112L
#define _ISOC99_SOURCE
#define __EXTENSIONS__
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
void
my_cleanup(void *arg)
{
printf("cleanup: %s\n", (char *)arg);
}
void *
thread_stuff(void *arg)
{
printf("thread started\n");
pthread_cleanup_push(cleanup, "running");
if (arg)
pthread_exit((void *)2);
pthread_cleanup_pop(0);
pthread_exit((void *)2);
}
int
main()
{
int err;
pthread_t tid1, tid2;
err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);
sleep(10); /* change the value here if you want */
return SUCCESS;
}
When this code is run, the message from the cleanup function is printed twice, as it should be, but other times when it is run, I see the message printed only once sometimes, and other times I see it printed three times or not at all. You add in the sleep function in the main function to play with how long it takes the main function to terminate.
What can I do to make the program run as it should? I suspect it has something to do with joining to the children, but I don't entirely understand the concept of a join or how to apply it to this situation.
Thanks in advance!
Yes, you should "join" the threads. "Joining" a thread simply means waiting until the thread has terminated. In other words, you would do
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
to wait until both threads have terminated.
Edit: What to do if you have a child thread which, in turn, creates a "grandchild" thread? As a rule, whoever created the thread should wait for it to terminate ("join" it). So in this scenario, the child thread would call phtread_join on the grandchild thread, and the main thread would call join on the child thread.
I think you want to run pthread_join on each of the threads when your main thread completes -- this makes the main thread stop until the given thread finishes running. Other threads can still complete first though, so running pthread_join on every thread will prevent the main thread from terminiating until all of the others have terminated.
There is a definite problem if main() finishes before the threads it spawned if you don't call pthread_exit() explicitly. All of the threads it created will terminate because main() is done and no longer exists to support the threads.
By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done.
int main()
{
int err;
pthread_t tid1, tid2;
err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);
sleep(10); /* change the value here if you want */
/* Add the pthread_exit */
pthread_exit(NULL);
return SUCCESS;
}
Refer for more info here