在线程中使用sleep()

时间:2015-04-11 18:44:47

标签: c multithreading pthreads

我是线程及其执行的整个概念的新手。我一直致力于一个程序,以进一步了解它们的工作方式。

这是我的代码:

#include <stdio.h>
#include <pthread.h>
int glob;
void *child(void *t);
pthread_t thread[10];


void *child(void *t)
{
    // Increment glob by 1, wait for 1 second, then increment by 1 again.
    printf("Child %d entering. Glob is currently %d\n", t, glob);
    glob++;
    sleep(1);
    glob++;

    printf("Child %d exiting. Glob is currently %d\n", t, glob);
}
int main()
{
    int i;
    glob=0;
    for(i=0; i<10; i++)
    {
        pthread_create(&thread[i], NULL, child, (void *) i ) ;
    }
    printf("Final value of glob is %d\n", glob);
    return 0;
}

虽然我知道他们的执行时间是不可预测的。因此,glob的打印和更新将被搞砸。但是,在睡眠(1)完全执行之后,为什么不是线程的后半部分呢?

感谢任何帮助。

我目前的输出:

Child 0 entering. Glob is currently 0
Child 3 entering. Glob is currently 0
Child 2 entering. Glob is currently 0
Child 1 entering. Glob is currently 0
Child 4 entering. Glob is currently 3
Child 5 entering. Glob is currently 5
Child 6 entering. Glob is currently 6
Child 7 entering. Glob is currently 7
Child 8 entering. Glob is currently 8
Final value of glob is 9
Child 9 entering. Glob is currently 9

1 个答案:

答案 0 :(得分:3)

由于您的主线程不等待线程,因此主线程可能会退出之前线程可以在sleep()之后打印部件。因此,退出整个过程。

从main为所有线程调用pthread_join(),您将看到打印sleep()后调用printf。您已经知道,所有线程更新glob时都会出现竞争条件。所以你对这个程序没有多大意义。