【发布时间】:2015-11-05 14:14:43
【问题描述】:
如何重现输出:
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int myglobal;
void *thread_function(void *arg) {
int i,j;
for ( i=0; i<20; i++ ) {
j=myglobal;
j=j+1;
printf(".");
fflush(stdout);
sleep(1);
myglobal=j;
}
return NULL;
}
int main(void) {
pthread_t mythread;
int i;
myglobal = 0;
if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
printf("error creating thread.");
abort();
}
for ( i=0; i<20; i++) {
myglobal=myglobal+1;
printf("o");
fflush(stdout);
sleep(1);
}
if ( pthread_join ( mythread, NULL ) ) {
printf("error joining thread.");
abort();
}
printf("\nmyglobal equals %d\n",myglobal);
exit(0);
}
输出:
o..oo..oo..oo..oo..oo..oo..oo..oo..oo..o
myglobal 等于21
问题:
有人能解释一下这个输出是如何产生的吗? 为什么不像“o.o.o.o.”那样交替使用呢?
【问题讨论】:
-
你应该先了解线程是什么!有足够的信息可以找到。懒得看维基百科?为什么你希望他们交替执行?
-
我期望的输出是:“o.o.o.o”等等。我不明白一个线程如何超越另一个线程。
-
我不知道你是否理解我的问题。我将再次尝试解释:我们有两个线程。一个打印“。”并停顿一秒钟。另一个打印“o”并暂停一秒钟。怎么可能连续有两个“oo”和“..”?
-
没有人注意到有
sleep调用应该强制交替?这在我的机器上完美交替。 -
睡眠的作用是它可能会或可能不会生成上下文切换。您无法知道其他进程执行其时间片所需的时间。所以 sleep 的意思是:“睡 1 秒或更长时间,或者什么”。 Linux(或任何操作系统)不是 RTOS。所以这里没有保证的行为。此外,这里可能存在竞争条件,因为两个线程都写入同一个变量。此外,从几个不同的线程调用 stdio 函数是有问题的做法。
标签: c multithreading pthreads posix