繁体   English   中英

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

[英]how to execute parent befor child thread - pthreads in c

我想使父进程在子线程之前执行。 我不确定我要去哪里弄错我的程序正在输出的顺序。

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);
    }
}

输出:

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

排除并发执行的最简单方法是锁定。 在调用pthread_create之前,让“父”(原始线程)进行锁定,并仅在准备好“子”(新线程)运行时将其解锁。 “孩子”应该在做任何事情之前先上锁; 然后,如果需要,它可以立即将其解锁,或者保留它以控制对共享状态的访问。

暂无
暂无

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

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