简体   繁体   中英

How do you create a thread that create another thread in C programing?

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;


}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM