0

I'm having trouble creating a thread within a thread. I need to create thread1 and thread1 does "something" as well as creating thread2 which will do something else.

my code:

    #include <pthread.h>
   #include <stdio.h>
   #include <errno.h>
   #include <stdlib.h>
   #include <unistd.h>

void *msg1(void *ignored)
{

void *msg2(void *ignored)
{
printf("this is thread2");
}


pthread_t thread;
int thread2;
thread2 = pthread_create(&thread, NULL, msg2, NULL);

return 0;
}



int main () 
{
pthread_t thread;
int thread1;
thread1 = pthread_create(&thread, NULL, msg1, NULL);
return 1;


}
0

1 Answer 1

3

Creating threads from inside a thread callback is no different from creating them from the main thread. Naturally each thread will need its own callback function - which is declared with the given format for pthreads, void* func (void*).

For reasons unknown, you try to declare a function inside another function. That doesn't make any sense and isn't allowed in C. Threads or no threads.

If you wish to limit the scope of the second thread, then put both thread callbacks in a module of their own, and make the second callback function static. It is very fundamental program design - something I'd recommend studying long before taking on multi-threading.

Sign up to request clarification or add additional context in comments.

1 Comment

Technically, two threads that should have the same behavior could of course run the same thread function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.