简体   繁体   中英

how to execute parent befor child thread - pthreads in c

I want to make it so that parent process executes before the child thread does. I'm not sure where I'm going wrong to get the order my program is outputting.

int status = 0;

void *print_child(void *arg)
{

    while (status == 0)
    {
        printf("Signal hasn't changed..\n");
        sleep(1);

    }
    printf("The child has started...\n");
    printf("The child is done! \n ");
}

int main()
{
    pthread_t child;
    pthread_create(&child, NULL, &print_child, NULL);

    sleep(2);
    printf("The parent has started...\n");
    printf("The parent is done! \n");

    status++;

    if (pthread_join(child, NULL))
    {
        printf("ERROR");
        exit(1);
    }
}

OUTPUT:

signal has changed
signal has changed
parent has started
parent is done
child has started
child is done

The simplest way to exclude concurrent execution is a lock. Have the "parent" (original thread) take a lock before calling pthread_create , and only unlock it when it's ready for the "child" (new thread) to to run. The "child" should take the lock before doing anything; it can then unlock it immediately if it wants, or keep it to control access to shared state.

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