简体   繁体   English

如何执行父befor子线程-C中的pthreads

[英]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. 在调用pthread_create之前,让“父”(原始线程)进行锁定,并仅在准备好“子”(新线程)运行时将其解锁。 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. 然后,如果需要,它可以立即将其解锁,或者保留它以控制对共享状态的访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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