儿童线程睡觉而不是主线程

时间:2015-02-21 13:10:59

标签: c linux multithreading sleep

这是关于问题Why are all of my threads sleeping using sleep()?

这是代码:

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];

void* doSomeThing()

{
    unsigned long i = 0;
    pthread_t id = pthread_self();

    if (pthread_equal(id,tid[0]))
    {
        printf("\n First thread processingn");
    }
    else
    {
        printf("\n Second thread processingn");
    }
    return NULL;
}

int main(void)
{
    int i = 0;
    int err;
    while (i < 2)
    {
        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
        sleep(5);
        if (err != 0)
            printf("\ncan't create thread [%s]", strerror(err))
            else

                printf("\n Thread created successfullyn");
        i++;
        // sleep(5);
    }
    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);

    return 0;
}

这是我的输出:

First thread processingn
Thread created successfullyn
Second thread processingn
Thread created successfullyn

前两行在5秒后显示,接下来的两行在5秒后显示。为什么子线程变得睡眠而不是主线程? o / p不应该有任何滞后打印,不是吗?

0 个答案:

没有答案